hi guys,

i have created a datagridview with a combobox, which pulls out info from my DB,
what i am trying to do now is, populate the rest of the datagridview with the information linked to the selection.

failing that i want to populate a label with the selected item.

any ideas guys?

many thanks
Ade

Recommended Answers

All 16 Replies

If you click or move to a cell containing data, the label will contain a copy of it with this code:

private void MyDGV_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (MyDGV[e.ColumnIndex, e.RowIndex].Value != null)
            {
                MyLabel.Text = MyDGV[e.ColumnIndex, e.RowIndex].Value.ToString();
            }           
        }

Hi DDanbe,

cheers that works great, bit better than what i got.

do you know the best way for me to code in the rest of the DGV columns with the selected item in the combobox?

many thanks

Do you mean the rest of the DGV should be filled with the same selected item from a combobox?
Or do you mean to fill a DGV column with all the items from the combobox?
Or something else?

i mean,
for example, at the moment, the combobox in the DGV is populated with weeks (1 to 52), what i want, is when i select on say 'week 3' that the WeekID would be populated in the next column.

Still don't get it I'm afraid do you talk about a DataGridViewComboBoxColumn?

yea, the combobox is a datagridviewcomboboxcolumn
:)

So every row basically has a parameter and based on that parameter you want to populate the current rows columns?

yea, set on the selection of the datagridviewcomboboxcolumn

You can just build a simple select query and in the where specify you value. Initialize a DataReader and insert the values based on the current row index.

yea i know the theory behind it, just not the code..
ok maybe im asking the wrong questions,
does anyone know of a book that could help me?

Hi
i am new in this so how use label data

what do you mean JerryTom?
what do you want to use label data for? sometimes i Use label data as variables

You basically need an onChangeEvent for the datagridviewcomboboxcolumn. And this will need to be created. I used this in a previous project Click Here As for selecting the data. You have the selected value in the combobox and the event for populating the rest of the columns.

In the DoSomeStuff(); Section you add something like the following

SqlConnection con = new SqlConnection(@"Data Source=YourDataSourceName;Initial Catalog=DatabaseName;Integrated Security=False;User ID=[User];Password=[Password]");
string Command = "SELECT WeekNumber FROM Weeks WHERE WeekID = "+combo.SelectedItem.ToString().Replace(System.Environment.NewLine,"")+"";
SqlCommand com = new SqlCommand(Command, con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
  dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[dataGridView1.CurrentCell.ColumnIndex+1].Value = reader[0].ToString();
  //Adds data to column right next to combobox column at the specified index
}
con.Close();

ok il give it a go, thank you. will report back.

nope can't get that working :/
however, i have tried something, which gets the Week_ID and puts it into the column, but it duplicates, would anyone mind taking a look, to see what i've done wrong?

        private void btn_BigButton_Click(object sender, EventArgs e)
        {

            String ConnString = Connection.ConnString;
            conn = new OleDbConnection(ConnString);

            conn.Open();                            //Open Connection to Database
            sql = "SELECT * FROM tbl_Weeks;";       //query to pull all the weeks out
            DataTable data = null;                  //datatable variable set to null
            data = new DataTable();                 //data equals a new datatable
            da = new OleDbDataAdapter(sql, conn);   //da set to new dataadapter then brings in the query and connection
            da.Fill(data);                          //fill the 'da' dataadapter

            dataGridView1.ColumnCount = 3;
            dataGridView1.Columns[0].Name = "Product ID";

            DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
            cmb.HeaderText = "Select Data";
            cmb.Name = "cmb";
            cmb.MaxDropDownItems = 4;


            for (int i = 0; i < data.Rows.Count; i++)
            {
                string data1 = data.Rows[i]["Weeks"].ToString();    //data1 set to all the records in the "Weeks" field

                string data2 = data.Rows[i]["Week_ID"].ToString();

                Thread.Sleep(50);
                Refresh();
                label3.Text = i.ToString();
                cbox_testing.Items.Add(data1 + " " + data2);                         //populate the combobox with the data1 records
                label2.Text = data2.ToString();
                cmb.Items.Add(data1);

                label3.Text = data2.ToString();

            }
            // ############################################################################################################################## //
            dataGridView1.Columns.Add(cmb);
            dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);

        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            ComboBox combo = e.Control as ComboBox;
            if (combo != null)
            {
                combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
                combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
            }
        }

        private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cbox = (ComboBox)sender;
            string item = cbox.Text;
            if (item != null)

            label1.Text = item;
            DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[thisrow];// .Clone();
            String ConnString = Connection.ConnString;
            conn = new OleDbConnection(ConnString);

            conn.Open();                            //Open Connection to Database
            sql = "SELECT * FROM tbl_Weeks WHERE Weeks = '" + label1.Text + "';";       //query to pull all the weeks out
            DataTable data1 = null;                  //datatable variable set to null
            data1 = new DataTable();                 //data equals a new datatable
            da = new OleDbDataAdapter(sql, conn);   //da set to new dataadapter then brings in the query and connection
            da.Fill(data1);                          //fill the 'da' dataadapter

            for (int i = 0; i < data1.Rows.Count; i++)
            {
                label3.Text = i.ToString();
                string data2 = data1.Rows[i]["Week_ID"].ToString();
                label2.Text = data2.ToString();
                dataGridView1.Rows[i].Cells["Product ID"].Value = label2.Text;
                if (dataGridView1.Rows[i].Cells["Product ID"] != null)
                {
                    dataGridView1.Rows.Add(label2.Text);
                }
            }

I tested the code i provided and it works perfectly what difficulties are you experiencing? I populate a datagridcombobox with all the weeks and every time you select a week it populates the other columns in the row of the combobox based on the selection with data it fetches from SQL.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.