How to bind data in a column with datagridview list data

Here are the contacts, but we can have multiple contacts, so I want to show the list in the combobox

DataTable dt = new DataTable();
dt = MainClass.GetDatabyQuery("select * from tbl");

if (dt.Rows.Count > 0)
{
    dgv_ClientDetail.DataSource = dt;
}

      

I have this method to fetch values ​​from database in datagridview, but I need one datagridview data column column and want to bind data in one flight and in dgv texboxes. If anyone knows, then tell me. There are three columns Name, City, Contacts. I want to show multiple contacts in a combobox dgv column

+3


source to share


3 answers


Just select only Name

and City

in dt

so you can do something like

        dgv_ClientDetail.DataSource = dt;
        DataGridViewComboBoxColumn dgvCboColumn = new DataGridViewComboBoxColumn();
        dgvCboColumn.Name = "Contacts";
        dgvCboColumn.DataSource = dtContacts; //DataTable that contains contact details
        dgvCboColumn.DisplayMember = "Name";
        dgvCboColumn.ValueMember = "Id";
        dataGridView1.Columns.Add(dgvCboColumn);

      

EDIT:



        dgv_ClientDetail.DataSource = new DataView(dt)
                                         .ToTable(true, new string[] { "Name", "City" });
        DataGridViewComboBoxColumn dgvCboColumn = new DataGridViewComboBoxColumn();
        dgvCboColumn.Name = "Contacts";
        dgv_ClientDetail.Columns.Add(dgvCboColumn);
        foreach (DataGridViewRow row in dgv_ClientDetail.Rows)
        {
            DataGridViewComboBoxCell cboContacts = (DataGridViewComboBoxCell)
                                                         (row.Cells["Contacts"]);
            cboContacts.DataSource = //Get the contact details of a person,
                                     //using his Name or Id field (row.Cells["Name"]);
            cboContacts.DisplayMember = "Name"; //Name column of contact datasource
            cboContacts.ValueMember = "Id";//Value column of contact datasource
        }

      

Hope it helps ...

+2


source


Try something like this

// Loop through rows and get each combobox

foreach (DataGridViewRow row in dgv_ClientDetail.Rows)
{
     DataGridViewComboBoxCell ContactCombo = (DataGridViewComboBoxCell)(row.Cells[index of Contact column]);

     ContactCombo.DataSource = // your contacts datasource;
     ContactCombo.DisplayMember = "name of field to be displayed like say ContactName";
     ContactCombo.ValueMember = "Id";
}

      



Edit: you need to set the ValueMember for the combobox too

0


source


Try this: -

First, just enter the data key into the DataGridView for the contact. And in ItemDatabound events, just use datakey to filter for each Dataitem with that DataGridView.

0


source







All Articles