C# DatagridViewRow.Cells.Add方法不工作
我有一个windows窗体,其中有一个DataGridView,我正在尝试遍历所有DataGridView行,在两列之后添加一个comboboxcell 我的目标是有一个组合框列,它根据单元格[0]的值显示项目 这是我的代码,我无法向DataGridView行添加任何单元格。我做错了什么C# DatagridViewRow.Cells.Add方法不工作,c#,.net,winforms,datagridview,C#,.net,Winforms,Datagridview,我有一个windows窗体,其中有一个DataGridView,我正在尝试遍历所有DataGridView行,在两列之后添加一个comboboxcell 我的目标是有一个组合框列,它根据单元格[0]的值显示项目 这是我的代码,我无法向DataGridView行添加任何单元格。我做错了什么 private void UserAccessForm_Load(object sender, EventArgs e) { dataGridView1.DataSource = LoadData();
private void UserAccessForm_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = LoadData();
AddPermissions();
}
private DataTable LoadData()
{
ConnectionString = ConfigurationManager.ConnectionStrings["UserProfile"].ToString();
DataSet ds = new DataSet();
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
{
// Create the command and set its properties
sqlDataAdapter.SelectCommand = new SqlCommand();
sqlDataAdapter.SelectCommand.Connection = new SqlConnection(ConnectionString);
sqlDataAdapter.SelectCommand.CommandType = CommandType.Text;
// Assign the SQL to the command object
sqlDataAdapter.SelectCommand.CommandText = string.Format(Script.sqlGetLocalSystem);
sqlDataAdapter.Fill(dt);
}
return dt;
}
public void AddPermissions()
{
DataTable dPermissions = new DataTable();
long systemId = 0;
DataGridViewComboBoxCell comboBoxCell = null;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
ArrayList permissions = new ArrayList();
comboBoxCell = new DataGridViewComboBoxCell();
systemId = Convert.ToInt64(row.Cells[0].Value);
dPermissions = LoadPermissions(systemId);
foreach (DataRow dataRow in dPermissions.Rows)
{
permissions.Add(dataRow["UserLevelCategoryName"].ToString());
}
comboBoxCell.Items.AddRange(permissions.ToArray());
row.Cells.Add(comboBoxCell);
}
}
如何完成此操作?您不能将行的单元格集合添加到单元格集合。您应该将列添加到
列的集合DataGridView
,并将列表设置为列的.aspx)。还设置为要在combo中显示的数据源字段,并设置为数据源字段,以便在从combo中选择项目时将其值用作选定值
如果网格控件也绑定到数据源,并且创建此列以显示网格数据源中字段的值,请将列的值设置为要将此列绑定到的网格数据源的字段
DataTable permissions = LoadPermissions(); //Load all permissions
var column1 = new DataGridViewComboBoxColumn();
column1.Name = "column1";
column1.DataSource = permissions;
//a column from Permissions table to use its value when the user select from combo box
column1.ValueMember = "Id";
//a column from Permissions table to show its value in combo box
column1.DisplayMember = "Name";
//a column from datasourec table of your grid which you want to bind column to
column1.DataPropertyName = "PermissionId";
//Add column to grid
this.categoryDataGridView.Columns.Add(column1);
然后,如果要基于另一个单元格在每行的组合框中显示不同的项,您应该处理事件并获取编辑控件,并根据另一个单元格的值设置控件的DataSource
。您应该将datagridviewcomboxcolumn
添加到Columns
集合DataGridView
。谢谢,我明白您的意思。我尝试了您的解决方案,但问题是dataGridView1_EditingControlShowing事件没有被触发,因为我不必更改datagrid中的任何内容。。。自动加载数据网格时,我希望组合框也被加载。。。希望我这次清楚第一个问题是你在网格中添加单元格到单元格集合。这是错误的!您可以按照我在回答中描述的方式添加组合框列。然后问一个新问题,关于如何在组合框中有不同的项目。好的,是的,明白了。。感谢您的快速回复:)