【发布时间】:2014-10-13 18:49:50
【问题描述】:
我希望能够从下拉列表中选择一个项目,点击一个按钮,然后将该项目添加到 GridView 以供用户查看。现在,当我点击 + 按钮时,网格会显示,但单元格是空白的。有什么建议吗?
ASP 代码:
<tr>
<td valign="top" colspan="2">
<b>Agents Visited</b><br />
<asp:DropDownList SelectionMode="Multiple" runat="server" ID="agentsDropdown" Name="agentsDropdown" width="425"></asp:DropDownList>
</td>
<td valign="top">
<br />
<asp:Button id="agentButton" name="agentButton" runat="server" Text="+" OnClick="AddAgent" CssClass="buttonstyle" onmouseover="shade(this);" onmouseout="unshade(this);" />
</td>
</tr>
<tr>
<asp:GridView ID="agentGridView" Visible="False" AllowSorting="False" AllowPaging="False" Runat="server" AutoGenerateColumns="False" PageSize="20" >
<Columns>
<asp:TemplateField HeaderText="Agent">
<ItemTemplate>
<asp:Label ID="agentName" runat="server" Text=''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:Label ID="agentValue" runat="server" Text=''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</tr>
初始 GridView 绑定:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack
agentGridView.DataSource = Nothing
agentGridView.Databind()
End If
End Sub
后面的附加代码:
Protected Sub AddAgent(sender As Object, e As EventArgs)
If agentsDropdown.SelectedIndex > 0 Then
Dim dt As New DataTable
dt.Columns.Add("agentName")
dt.Columns.Add("agentValue")
Dim row1 As DataRow = dt.NewRow
row1.Item("agentName") = agentsDropdown.SelectedItem.Text.ToString()
row1.Item("agentValue") = agentsDropdown.SelectedValue.ToString()
dt.Rows.Add(row1)
agentGridView.DataSource = dt
agentGridView.DataBind()
agentsDropdown.SelectedIndex = 0
Dim agentRowsCount as Integer = agentGridView.Rows.Count
If agentRowsCount > 0
agentGridView.Visible = True
End If
End If
End Sub
【问题讨论】:
-
您是否已单步执行您的代码。这里只是一个猜测,但每次进入这里时,您都会不断创建一个新的数据表。那么,当您进行选择时,您是否触发了选定的索引更改事件?因为在您的代码中,您再次设置了agentDropdown.SelectedIndex = 0,这可能会再次触发它并创建一个新的空表。看看你是不是进了两次。
-
我目前不在 Visual Studio 中工作,因此单步执行后面的代码很痛苦。但是,注释掉 SelectedIndex = 0 不会产生任何变化。