我正在尝试从列表中填充DGV。 Datagridview是可编辑的,并指定了特定的列类型。即Textbox,Combobox,Checkbox。
如果我使用DGV.Datasource = MyList,它会将我T的所有属性添加到指定列后的DGV 。 (例如地址1,县,市,ID,地址1,县,市)
Addresses = New List(Of Address)
Dim a1 = New Address(Guid.NewGuid())
a1.Address1 = "Address 1"
a1.County = "County Test"
a1.City = "My City"
Addresses.Add(a1)
Dim a2 = New Address(Guid.NewGuid())
a2.Address1 = "Address 1"
a2.County = "County Test"
a2.City = "My City"
Addresses.Add(a2)
Dim a3 = New Address(Guid.NewGuid())
a3.Address1 = "Address 1"
a3.County = "County Test"
a3.City = "My City"
Addresses.Add(a3)
uxAddresses.DataSource = Addresses
如果我循环,如下所示,它将第一行设置为罚款,但不设置第2行或第3行(在我的测试对象中)。
Private Sub DataGridViewPaint(ByVal la As List(Of Address),
ByVal paramDgv As DataGridView)
Dim intDr As Integer = 0
For Each g In la
paramDgv.Rows(intDr).Cells("ID").Value = g.Id
paramDgv.Rows(intDr).Cells("Address1").Value = g.Address1
paramDgv.Rows(intDr).Cells("County").Value = g.County
paramDgv.Rows(intDr).Cells("City").Value = g.City
intDr += 1
Next
End Sub
这让我想知道,实现这一点的正确方法是什么,因为我觉得我在这里错过了什么....谢谢
答案 0 :(得分:1)
您不必一次一行地向网格视图添加列表。你可以将整个列表绑定到网格视图,如下所示:
<asp:GridView ID="GridView1" runat="server" AllowSorting="False"
AutoGenerateColumns="false" BackColor="White"
BorderWidth="2px" BorderStyle="Solid"
CellPadding="4" ForeColor="#333333" GridLines="both"
EmptyDataText="No Log Messages">
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField Visible="false" ItemStyle-HorizontalAlign="Center" HeaderText="ID" HeaderStyle-ForeColor="white">
<ItemTemplate>
<asp:Label ID="lblId" runat="Server" Text=' <%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false" ItemStyle-HorizontalAlign="Center" HeaderText="Address" HeaderStyle-ForeColor="white">
<ItemTemplate>
<asp:Label ID="lblAddress" runat="Server" Text=' <%#Eval("Address1")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
然后绑定源:
Addresses = New List(Of Address)
'file the list
me.GridView1.dataSource = Addresses
me.GridView1.DataBind()
只需确保客户端gridview中的代码:&lt;%#Eval(“Address1”)%&gt; 匹配对象列表中属性的名称。
答案 1 :(得分:1)
您可以尝试使用DataGridViewColumn.DataPropertyName
属性,如下所示:
Column1.DataPropertyName = "Address1"
Column2.DataPropertyName = "County"
Column3.DataPropertyName = "City"
Column4.DataPropertyName = "ID"
之后,设置DGV.Datasource = MyList
。
附加说明:您需要设置每个列的DataPropertyName
字段,否则您最终可能会出现重复列。