我有一个数据网格和一个数据库绑定在一起,我正在使用vb.net和vs2012。我的问题不是数据库中的所有列都会显示在数据网格中,这取决于用户他想要显示的列(表单中有一个复选框用于选择要显示的列)并且数据库中必须有一列分开(我在这里使用拆分)。
这是我的示例数据库:
Name | col1 | col2 | col3 |
---------------------------------------------
aa,bb,cc| 111 | 111 | 111 |
dd,ee,ff| 222 | 222 | 222 |
gg,hh,ii| 333 | 333 | 333 |
---------------------------------------------
在该示例中,db NAME COLUMN必须分开,
(我已经解决了)
这是我在 data-grid 和 split-ted 中添加列的示例代码:
Dim cl1 As New DataGridViewTextBoxColumn
Dim cl2 As New DataGridViewTextBoxColumn
Dim cl3 As New DataGridViewTextBoxColumn
With cl1
.HeaderText = "SplitName1"
.Name = "sn1"
.Width = 120
.ReadOnly = True
End With
With cl2
.HeaderText = "SplitName2"
.Name = "sn2"
.Width = 120
.ReadOnly = True
End With
With cl3
.HeaderText = "SplitName3"
.Name = "sn3"
.Width = 120
.ReadOnly = True
End With
dg.Columns.Insert(0, cl1)
dg.Columns.Insert(1, cl2)
dg.Columns.Insert(2, cl3)
'dynamic column
Dim n As Integer = 3
'here it count datatable columns if how many columns to make in datagrid
'I start in 1 because column 0 is NAME COLUMN
For colcnt As Integer = 1 To dt.Columns.Count - 1 'dt is datable
Dim dgvtxt As New DataGridViewTextBoxColumn
With dgvtxt
.HeaderText = "Column" & colcnt.ToString
.Name = "col" & colcnt.ToString
.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader
.ReadOnly = True
End With
dg.Columns.Insert(n, dgvtxt)
n += 1
Next
'this will be the variables to store the split names
Dim _SName1 As String = Nothing
Dim _SName2 As String = Nothing
Dim _SName3 As String = Nothing
'for splitting column name
Dim charSeparatorsC() As Char = {","c}
Dim sampDataArray() As String
dg.Rows.Clear()
'loop through records to get values
For counter As Integer = 0 To dt.Rows.Count - 1
'splitting procedure
sDataArray = dt2.Rows(counter)(0).ToString.Split(charSeparatorsC, StringSplitOptions.RemoveEmptyEntries)
'Load data on the sampDataArray to the Sample Name column variable
'If the array is not existing set an empty string
Try
_SName1 = sDataArray(0).ToString
Catch ex As Exception
_SName1 = ""
End Try
Try
_SName2 = sDataArray(1).ToString
Catch ex As Exception
_SName2 = ""
End Try
Try
_SName3 = sDataArray(2).ToString
Catch ex As Exception
_SName3 = ""
End Try
'Now this is my problem, how to add the dynamic selected columns
'from datable since the code below is specified column of a datagrid which is the cl1,cl2, and cl3.
'My question is how to get the columns from datatable and add to datagrid(sample output below).
dgRT.Rows.Add(_SName1, _SName2, _SName3)
Next
预期输出:
如果用户选择了两列来显示
|SplitName1|SplitName2|SplitName3|col1|col2|
|------------------------------------------|
| aa | bb | cc |111 |111 |
| dd | ee | ff |222 |222 |
| gg | hh | ii |333 |333 |
|------------------------------------------|
先感谢您!我需要一个帮助的想法。