小妹我现在是把ComboBox能放到DataGrid里,也同时能下拉出值来。可是我如何把所选的值显示到DataGrid里啊!现在是一点选择的值,根本DataGrid无变化还是原来的值。请各位师哥帮忙看看!或者有更好的方法给小妹解释一下。还有捎带问一个小问题!如何让DataGrid里其他内容无法编辑!都是WinFrom的程序。public ComboBox MyCombo=new ComboBox();
private void Form2_Load(object sender, System.EventArgs e)
{
try
{
SqlConnection conn=new SqlConnection("server=.;database=TrainingChina;user id=sa;password=sa"); conn.Open();
MyCombo.Name = "MyCombo";
MyCombo.Visible = false;
MyCombo.Items.Clear();
MyCombo.Items.Add("Sales Representative");
MyCombo.Items.Add("Inside Sales Coordinator");
MyCombo.Items.Add("Vice President, Sales");
MyCombo.Items.Add("Sales Manager");
MyCombo.Items.Add("Flunky");
Sql="select * from BT_command_By where sign='B001'";
SqlDataAdapter da = new SqlDataAdapter(Sql, conn);
DataSet ds = new DataSet();
da.Fill(ds,"BT_command_By");
dataGrid1.PreferredRowHeight = MyCombo.Height;
this.dataGrid1.DataSource = ds;
this.dataGrid1.DataMember="BT_command_By";
dataGrid1.Controls.Add(MyCombo);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}private void dataGrid1_Paint(object sender, PaintEventArgs e)
{
if(this.dataGrid1.CurrentCell.ColumnNumber == 3 )
{
MyCombo.Width = this.dataGrid1.GetCurrentCellBounds().Width;
}
}private void dataGrid1_CurrentCellChanged(object sender, EventArgs e)
{
if(this.dataGrid1.CurrentCell.ColumnNumber == 3)
{
MyCombo.Visible = false;
MyCombo.Width = 0;
MyCombo.Left = dataGrid1.GetCurrentCellBounds().Left;
MyCombo.Top = dataGrid1.GetCurrentCellBounds().Top;
MyCombo.Text = MyCombo.SelectedText;
MyCombo.Visible = true;
}
else
{
MyCombo.Visible = false;
MyCombo.Width = 0;
}
}
private void Form2_Load(object sender, System.EventArgs e)
{
try
{
SqlConnection conn=new SqlConnection("server=.;database=TrainingChina;user id=sa;password=sa"); conn.Open();
MyCombo.Name = "MyCombo";
MyCombo.Visible = false;
MyCombo.Items.Clear();
MyCombo.Items.Add("Sales Representative");
MyCombo.Items.Add("Inside Sales Coordinator");
MyCombo.Items.Add("Vice President, Sales");
MyCombo.Items.Add("Sales Manager");
MyCombo.Items.Add("Flunky");
Sql="select * from BT_command_By where sign='B001'";
SqlDataAdapter da = new SqlDataAdapter(Sql, conn);
DataSet ds = new DataSet();
da.Fill(ds,"BT_command_By");
dataGrid1.PreferredRowHeight = MyCombo.Height;
this.dataGrid1.DataSource = ds;
this.dataGrid1.DataMember="BT_command_By";
dataGrid1.Controls.Add(MyCombo);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}private void dataGrid1_Paint(object sender, PaintEventArgs e)
{
if(this.dataGrid1.CurrentCell.ColumnNumber == 3 )
{
MyCombo.Width = this.dataGrid1.GetCurrentCellBounds().Width;
}
}private void dataGrid1_CurrentCellChanged(object sender, EventArgs e)
{
if(this.dataGrid1.CurrentCell.ColumnNumber == 3)
{
MyCombo.Visible = false;
MyCombo.Width = 0;
MyCombo.Left = dataGrid1.GetCurrentCellBounds().Left;
MyCombo.Top = dataGrid1.GetCurrentCellBounds().Top;
MyCombo.Text = MyCombo.SelectedText;
MyCombo.Visible = true;
}
else
{
MyCombo.Visible = false;
MyCombo.Width = 0;
}
}
写代码,你具体实现什么功能不清楚,根据combo选择动态更新datagrid 的显示吗?选择的是查询条件吗?如果是重新改datagrid 的数据源
private void RefreshDataTable()
{
cmbTable.Items.Clear();
DataSet dsTableArray = new DataSet();
String strSel = "select Name from sysobjects where xtype='u' and status>=0";
SqlDataAdapter apTableArray = new SqlDataAdapter(strSel, theConnection);
SqlCommandBuilder cbTableArray = new SqlCommandBuilder(apTableArray);
apTableArray.Fill(dsTableArray, "sysobjects"); foreach(DataRow nRow in dsTableArray.Tables["sysobjects"].Rows)
{
cmbTable.Items.Add(nRow["Name"].ToString().Trim());
}
}// 一个按钮点击事件
// 显示所选择表的所有数据在DataGrid中
private void btnViewData_Click(object sender, System.EventArgs e)
{
String strTable = cmbTable.Text;
if(strTable.Length <= 0)
return;
String strSel = "SELECT * FROM " + strTable;
SqlDataAdapter theDataAdapter = new SqlDataAdapter(strSel, theConnection);
SqlCommandBuilder theComBuilder = new SqlCommandBuilder(theDataAdapter); theDataSet.Clear();
theDataAdapter.Fill(theDataSet, strTable);
myGrid.DataSource = theDataSet.Tables[strTable];
myGrid.CaptionText = strTable;
}
-------------------
更新DataGrid的DataSource(DataTable 或 DataView)如何让DataGrid里其他内容无法编辑
-------------------
设置DataGrid为readonly
本文将介绍如何在 System.Windows.Forms.DataGrid中切入使用ComboBox控件,主要包括三方面的内容。 1. 在DataGrid中加入ComboBox列; 2. 把在DataGrid中的修改保存到对应的网格;
3. 设置DataGrid中网格的焦点。
下面是整个源代码,一些功能可以看注释。using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;namespace DataGridTest
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dgdFunctionArea;
private DataTable dtblFunctionalArea;
private System.Windows.Forms.Button buttonFocus;
private System.ComponentModel.Container components = null; public Form1()
{
InitializeComponent();
PopulateGrid();
} protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
} #region Windows 窗体设计器生成的代码 private void InitializeComponent()
{
this.dgdFunctionArea = new System.Windows.Forms.DataGrid();
this.buttonFocus = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dgdFunctionArea)).BeginInit();
this.SuspendLayout();
//
// dgdFunctionArea
//
this.dgdFunctionArea.DataMember = "";
this.dgdFunctionArea.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgdFunctionArea.Location = new System.Drawing.Point(4, 8);
this.dgdFunctionArea.Name = "dgdFunctionArea";
this.dgdFunctionArea.Size = new System.Drawing.Size(316, 168);
this.dgdFunctionArea.TabIndex = 0;
//
// buttonFocus
//
this.buttonFocus.Location = new System.Drawing.Point(232, 188);
this.buttonFocus.Name = "buttonFocus";
this.buttonFocus.Size = new System.Drawing.Size(84, 23);
this.buttonFocus.TabIndex = 1;
this.buttonFocus.Text = "获取焦点";
this.buttonFocus.Click += new System.EventHandler(this.buttonFocus_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(332, 217);
this.Controls.Add(this.buttonFocus);
this.Controls.Add(this.dgdFunctionArea);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.dgdFunctionArea)).EndInit();
this.ResumeLayout(false); }
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
//初始化DataGrid
private void PopulateGrid()
{
//创建一个DataTable对象,包括四列,前三列为String,最后一列为Boolean。
dtblFunctionalArea = new DataTable ("FunctionArea");
string[] arrstrFunctionalArea = new string [3]{"Functional Area","Min","Max"};
DataColumn dtCol = null;
//创建String列
for(int i=0; i< 3;i++)
{
dtCol = new DataColumn(arrstrFunctionalArea[i]);
dtCol.DataType = Type.GetType("System.String");
dtCol.DefaultValue = "";
dtblFunctionalArea.Columns.Add(dtCol);
} //创建Boolean列,用CheckedBox来显示。
DataColumn dtcCheck = new DataColumn("IsMandatory");
dtcCheck.DataType = System.Type.GetType("System.Boolean");
dtcCheck.DefaultValue = false;
dtblFunctionalArea.Columns.Add(dtcCheck); //把表绑定到DataGrid
dgdFunctionArea.DataSource = dtblFunctionalArea; //为DataGrid加载DataGridTableStyle样式
if(!dgdFunctionArea.TableStyles.Contains("FunctionArea"))
{
DataGridTableStyle dgdtblStyle = new DataGridTableStyle();
dgdtblStyle.MappingName = dtblFunctionalArea.TableName;
dgdFunctionArea.TableStyles.Add(dgdtblStyle);
dgdtblStyle.RowHeadersVisible = false;
dgdtblStyle.HeaderBackColor = Color.LightSteelBlue;
dgdtblStyle.AllowSorting = false;
dgdtblStyle.HeaderBackColor = Color.FromArgb(8,36,107);
dgdtblStyle.RowHeadersVisible = false;
dgdtblStyle.HeaderForeColor = Color.White;
dgdtblStyle.HeaderFont = new System.Drawing.Font("Microsoft Sans Serif", 9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
dgdtblStyle.GridLineColor = Color.DarkGray;
dgdtblStyle.PreferredRowHeight = 22;
dgdFunctionArea.BackgroundColor = Color.White; //设置列的宽度
GridColumnStylesCollection colStyle = dgdFunctionArea.TableStyles[0].GridColumnStyles;
colStyle[0].Width = 100;
colStyle[1].Width = 50;
colStyle[2].Width = 50;
colStyle[3].Width = 80;
} DataGridTextBoxColumn dgtb = (DataGridTextBoxColumn)dgdFunctionArea.TableStyles[0].GridColumnStyles[0]; ComboBox cmbFunctionArea = new ComboBox();
cmbFunctionArea.Items.AddRange(new object[]{"选项一","选项二","选项三"});
cmbFunctionArea.Cursor = Cursors.Arrow;
cmbFunctionArea.DropDownStyle= ComboBoxStyle.DropDownList;
cmbFunctionArea.Dock = DockStyle.Fill; //在选定项发生更改并且提交了该更改后发生 cmbFunctionArea.SelectionChangeCommitted += new EventHandler(cmbFunctionArea_SelectionChangeCommitted); //把ComboBox添加到DataGridTableStyle的第一列 dgtb.TextBox.Controls.Add(cmbFunctionArea); } //设置焦点模拟 private void GetFocus(int row,int col)
{
//先把焦点移动到DataGrid
this.dgdFunctionArea.Focus();
//把焦点移动到DataGridCell
DataGridCell dgc = new DataGridCell(row,col);
this.dgdFunctionArea.CurrentCell = dgc;
DataGridTextBoxColumn dgtb = (DataGridTextBoxColumn)dgdFunctionArea.TableStyles[0].GridColumnStyles[col]; //设置焦点 dgtb.TextBox.Focus();
} //把Combobox上修改的数据提交到当前的网格 private void cmbFunctionArea_SelectionChangeCommitted(object sender, EventArgs e)
{
this.dgdFunctionArea[this.dgdFunctionArea.CurrentCell] = ((ComboBox)sender).SelectedItem.ToString(); } //设置新的焦点 private void buttonFocus_Click(object sender, System.EventArgs e)
{
//焦点模拟,这里设置第三行第一列
GetFocus(2,0);
}
}}
总结,这里是通过DataGridTextBoxColumn.TextBox.Controls.Add方法实现在列中添加ComboBox控件;对于数据的保存是使用ComboBox.SelectionChangeCommitted事件来完成;设置焦点是通过DataGridTextBoxColumn.TextBox.Focus方法来实现。另外通过这个方法也可以添加DateTimePicker等类似的控件。
this.dataGridTextBoxColumn1.ReadOnly = true;//其他列只读
DataGridComboBoxColumn dataGridBoolColumn1 = new DataGridComboBoxColumn();
this.dataGridTableStyle2.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] {dataGridBoolColumn1 }using System;
using System.Data;
using System.Windows.Forms;
using System.Drawing;namespace Test
{
/// <summary>
/// DataGridComboBox 的摘要说明。
/// </summary>
public class DataGridComboBox:System.Windows.Forms.ComboBox
{
protected override bool ProcessKeyMessage(ref Message m)
{
// Keep all the keys for the DateTimePicker.
return ProcessKeyEventArgs(ref m);
} public DataGridComboBox()
{
this.Items.Add("werwe");
this.Items.Add("fghdfg");
this.Items.Add("ljkllkj");
this.Items.Add("wery");
}
}
}
using System;
using System.Data;
using System.Windows.Forms;
using System.Drawing;namespace Test
{
/// <summary>
/// DataGridComboBoxColumn 的摘要说明。
/// </summary>
public class DataGridComboBoxColumn:DataGridColumnStyle
{
private DataGridComboBox myComboBox = new DataGridComboBox(); // The isEditing field tracks whether or not the user is
// editing data with the hosted control.
private bool isEditing;
private bool m_CheckBoxVisible = false; public DataGridComboBoxColumn() : base()
{
myComboBox.Visible = false;
myComboBox.MaxDropDownItems = 20;
} public bool CheckBoxVisible
{
get{return m_CheckBoxVisible;}
set{m_CheckBoxVisible=value;this.myComboBox.Visible = m_CheckBoxVisible;}
} protected override void Abort(int rowNum)
{
isEditing = false;
myComboBox.SelectedIndexChanged -=
new EventHandler(this.ComboBoxSelectedIndexChanged);
Invalidate();
} protected override bool Commit
(CurrencyManager dataSource, int rowNum)
{
myComboBox.Bounds = Rectangle.Empty; myComboBox.SelectedIndexChanged -=
new EventHandler(this.ComboBoxSelectedIndexChanged); if (!isEditing)
return true; isEditing = false; try
{
string value = myComboBox.Text;
SetColumnValueAtRow(dataSource, rowNum, value);
}
catch (Exception)
{
Abort(rowNum);
return false;
} Invalidate();
return true;
} protected override void Edit(
CurrencyManager source,
int rowNum,
Rectangle bounds,
bool readOnly,
string displayText,
bool cellIsVisible)
{
string value = (string)GetColumnValueAtRow(source, rowNum);
if (cellIsVisible)
{
myComboBox.Bounds = new Rectangle
(bounds.X + 2, bounds.Y + 2,
bounds.Width - 4, bounds.Height - 4);
myComboBox.Text = value;
myComboBox.Visible = true;
myComboBox.SelectedIndexChanged +=
new EventHandler(this.ComboBoxSelectedIndexChanged);
}
else
{
myComboBox.Text = value;
myComboBox.Visible = false;
} if (myComboBox.Visible)
DataGridTableStyle.DataGrid.Invalidate(bounds); myComboBox.Focus();
} protected override Size GetPreferredSize(
Graphics g,
object value)
{
return new Size(100, myComboBox.PreferredHeight + 4);
} protected override int GetMinimumHeight()
{
return myComboBox.PreferredHeight + 4;
} protected override int GetPreferredHeight(Graphics g,
object value)
{
return myComboBox.PreferredHeight + 4;
} protected override void Paint(Graphics g,
Rectangle bounds,
CurrencyManager source,
int rowNum)
{
Paint(g, bounds, source, rowNum, false);
} protected override void Paint(
Graphics g,
Rectangle bounds,
CurrencyManager source,
int rowNum,
bool alignToRight)
{
Paint(
g, bounds,
source,
rowNum,
Brushes.Red,
Brushes.Blue,
alignToRight);
} protected override void Paint(
Graphics g,
Rectangle bounds,
CurrencyManager source,
int rowNum,
Brush backBrush,
Brush foreBrush,
bool alignToRight)
{
string s = (string)GetColumnValueAtRow(source, rowNum);
Rectangle rect = bounds;
g.FillRectangle(backBrush, rect);
rect.Offset(0, 2);
rect.Height -= 2;
g.DrawString(s,
this.DataGridTableStyle.DataGrid.Font,
foreBrush, rect);
} protected override void SetDataGridInColumn(DataGrid value)
{
base.SetDataGridInColumn(value);
if (myComboBox.Parent != null)
{
myComboBox.Parent.Controls.Remove (myComboBox);
}
if (value != null)
{
value.Controls.Add(myComboBox);
}
} private void ComboBoxSelectedIndexChanged(object sender, EventArgs e)
{
// Remove the handler to prevent it from being called twice in a row.
this.myComboBox.SelectedIndexChanged -= new EventHandler(ComboBoxSelectedIndexChanged);
this.isEditing = true;
base.ColumnStartedEditing(myComboBox);
}
}
}
关键是后面两段代码,是自定义的两个组件,简单说就是类似VS.NET2003中的System.Windows.Forms.DataGridBoolColumn的自定义dataGrid列
请参考以下的代码,这是我实际用的。
this.dataGridTextBoxColumn1.ReadOnly = true;//其他列只读
DataGridComboBoxColumn dataGridComboBoxColumn1 = new DataGridComboBoxColumn();
this.dataGridTableStyle2.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] {dataGridComboBoxColumn1 }