MRu
MRu

Reputation: 1395

C# - How to set value to default from table in combobox datagridview?

How can you set default value for combobox provided you get the value from table in database. I am thinking comparing the value with column [2]/destinationColumn to see which value in the table should be selected as default. This is my code so far which is wrong. Suggestion or an example code will be much appreciated. Thank you in advance guys.

                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;
                    }
                }

Upvotes: 1

Views: 331

Answers (1)

Sufyan Jabr
Sufyan Jabr

Reputation: 809

Things that i can see wrong

1- Your loop on the GridView wont work, do the loop on the Dataset instead of the Gridview...

2- You are comparing destinationColumn with cboDestinationColumns.DisplayMember which = "SOURCE_NAME" and you want If destinationColumn = "InvoiceNo"

3- Add the to the combo items using for loop and .add method, and do your if statement their.

To add the items:

1st add this class

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

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

Then loop on the Dataset

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;
}

Upvotes: 1

Related Questions