Filling ComboBox Column in DatagridView VB.Net

时间:2016-07-11 21:07:07

标签: vb.net visual-studio-2012 datagridview

i have a datagridview with 2 columns as combobox and i want to fill the second one depending on the first one.

Ex. I have a table in my database with stations

TableStations
Station 1 
Station 2

And each stations has a different amount of outputs

Ex.

Station 1      Station 2
OutP1            OutP5
OutP2            OutP6
                 OutP7

What i want to do in the datagridview is that when the user selects from the first combobox a station the next combobox gets filled with the outputs for that station, my problem comes when the user adds a second row in the datagridview if he selects a diferent station the info in the first row will be modified.

Is there any solution for this or any other way to do what i want?

Thanks in advance

EDIT: this is the code im using

                Con.Open()
                cmd.Parameters.Clear()
                With cmd
                    .CommandText = "Select output From List_outputs where station=@station"               
                    .Parameters.AddWithValue("@station", datagridview1.Item(0, e.RowIndex).Value)
                    .Connection = Con
                    reader = .ExecuteReader
                End With
                combobox2.Items.Clear()
                While reader.Read
                    combobox2.Items.Add(reader("output "))
                End While
                reader.Close()

This code is under the cellclick event of my datagridview.

1 个答案:

答案 0 :(得分:0)

这有点棘手,因为您无法设置列的数据源。设置列的数据源会影响整个列。您必须分别设置每个单元格的数据源。我会告诉你该怎么做。

首先在空表单中添加DataGridView。不要添加列,我们将按代码添加列。您不必在实际项目中按代码添加列,但请按照我在此示例中所做的操作。我添加注释以使代码易于理解。我选择创建两个类来保存Station和Output。这也是可选的,您可以使用DataReader并手动添加它们。希望这会对你有所帮助。

n.toArray()

<强>截图:

enter image description here