从SQL加载的DataGridViewComboBoxColumn中选择Item

时间:2013-11-12 16:01:17

标签: c# sql sql-server datagridview

这是SqlDataAdapter我用来填充dataGridView1但在填写之前我将DataGridViewComboBoxColumn添加到该datagridview所以我将能够选择存储在SQL中的ComboboxColumn中的项目。但我不确定它是如何实现的。

 dtSelectPronajem = new DataTable();
            SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM PRONAJEM WHERE NA_CISLKU=@NA_CISLKU", conn);
            SDA.SelectCommand.Parameters.AddWithValue("@NA_CISLKU", VybraneCisku);
            SDA.Fill(dtSelectPronajem);
            dataGridView1.DataSource = dtSelectPronajem;

创建DataGridViewComboBoxColumn:

private void EditDGV()
    {
        try
        {

            DataTable dtPlodiny = new DataTable();
                string sqlQuery = "SELECT PLODINA, CENAZAQ FROM PLODINY"; 
                using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
                {
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dtPlodiny);
                }

                cbColumn = new DataGridViewComboBoxColumn();
                cbColumn.DataSource = dtPlodiny; //Changed with DataTable

                //add next two rows
                cbColumn.DisplayMember = "PLODINA";
                cbColumn.ValueMember = "PLODINA"; //property from .Datasource you want use as Value - reference to DataPropertyName

                cbColumn.DropDownWidth = 100;
                dataGridView1.Columns.Add(cbColumn);
                cbColumn.HeaderText = "Položka";
                this.cbColumn.Name = "POLOZKAcb";

        }

我的问题是 - 对于从SQL加载的每一行,ComboBox中的SelectText怎么可能?然后应在ComboBox中选择为SelectedText的值位于名为PLODINA的SQL列中。

非常感谢你的时间。

1 个答案:

答案 0 :(得分:2)

在设置DataGridViewColumn之前,必须将DataGridView添加到.DataSource

然后为新列设置.DataPropertyName

cbColumn.DataPropertyName = "PLODINA"

DataPropertyName必须是“PRONAJEM”表中字段的名称 然后选择.ValueMember = PRONAJEM.PLODINA(from DataTable)

的组合框列表