C# - 如何在combobox datagridview中将值设置为默认值?

时间:2016-06-27 05:03:10

标签: c# datagridview combobox

如果从数据库中的表中获取值,如何设置组合框的默认值。我正在考虑将值与列[2] / destinationColumn进行比较,以查看应该将表中的哪个值选为默认值。到目前为止这是我的代码,这是错误的。建议或示例代码将非常感谢。提前谢谢你们。

                string sqlLookupColumn = "SELECT LookUpColumnID, SOURCE_NAME FROM TB_LOOKUP_COLUMN ORDER BY SOURCE_NAME ASC";
                DataSet dsColumn = databaseManager.GetData(sqlLookupColumn);
                DataGridViewComboBoxColumn dgvCboColumn = new DataGridViewComboBoxColumn();
                dgvCboColumn.Name = "DESTINATION_NAME";
                dataGridView1.Columns.Add(dgvCboColumn);

                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    DataGridViewComboBoxCell cboDestinationColumns = (DataGridViewComboBoxCell)(row.Cells[3]);
                    cboDestinationColumns.DataSource = dsColumn.Tables[0];
                    string destinationColumn = row.Cells[2].Value.ToString();
                    cboDestinationColumns.DisplayMember = "SOURCE_NAME"; 
                    cboDestinationColumns.ValueMember = "LookUpColumnID";
                    if (destinationColumn == cboDestinationColumns.DisplayMember)
                    {
                        cboDestinationColumns.Selected = true;
                    }
                }

1 个答案:

答案 0 :(得分:1)

我看错的事情

1-你在GridView上的循环不起作用,在Dataset而不是Gridview上循环...

2-您正在将destinationColumn与cboDestinationColumns.DisplayMember进行比较,其中=“SOURCE_NAME”并且您想要If destinationColumn = "InvoiceNo"

3-使用for循环和.add方法添加到组合项目,然后执行if语句。

添加项目:

首先添加此课程

public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

然后循环数据集

for(int i=0;i<ds.Tables[0].Rows.Count;i++)
{
    DataRow dr = ds.Tables[0].Rows[i];
    ComboboxItem tmp= new ComboboxItem();
    tmp.Text = dr["SOURCE_NAME"];
    tmp.Value = dr["LookUpColumnID"];

cb.Items.Add(tmp);
if(dr["InvoiceNo"].ToString() =="")//Your condition here to set selected
cb.SelectedIndex = i;
}