您好我有一个包含几个文本框的表格,当用户点击该按钮时,它会被添加到gridview中。它与Shared dtValues As New DataTable()工作正常,但我遇到了其他问题所以我将其更改为Public ....按下按钮是我得到错误列'Qty'不属于该表。有什么建议吗?
ASPX
<asp:Table ID="tblPrice" runat="server" GridLines ="Both">
<asp:TableRow>
<asp:TableCell>QTY.</asp:TableCell>
<asp:TableCell>MATERIAL</asp:TableCell>
<asp:TableCell>COST</asp:TableCell>
<asp:TableCell>PRICE</asp:TableCell>
<asp:TableCell>TOTAL</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtQty" runat="server" Width="40" Text = "1"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtMaterials" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtCost" runat="server" Width="125" Text = "0" ></asp:TextBox>
<asp:MaskedEditExtender ID="meeCost1" runat="server" Mask="99,999,999.99" DisplayMoney="Left" TargetControlID="txtCost" MaskType="Number">
</asp:MaskedEditExtender>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtPrice" AutoPostBack="true" runat="server" Width="125" Text = "0" OnTextChanged = "PriceChange"></asp:TextBox>
<asp:MaskedEditExtender ID="meePrice1" runat="server" Mask="99,999,999.99" DisplayMoney="Left" TargetControlID="txtPrice" MaskType="Number">
</asp:MaskedEditExtender>
</asp:TableCell>
<asp:TableCell>
<asp:Label ID="lblTotal" runat="server" Text="$0.00"></asp:Label>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:Button ID="btnAddPurchase" runat="server" Text="Add Purchase" OnClick="btnAddPurchase_Click" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
<br />
<asp:GridView ID="gvPurchases" runat="server" AutoGenerateColumns="False"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
AutoGenerateSelectButton="True" >
</asp:GridView>
代码背后
Public Class _Default
Inherits System.Web.UI.Page
Public dtValues As New DataTable()
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
CreateDataTable()
End If
End Sub
Protected Sub CreateDataTable()
dtValues.Columns.Add(New DataColumn("Qty"))
dtValues.Columns.Add(New DataColumn("Materials"))
dtValues.Columns.Add(New DataColumn("Cost"))
dtValues.Columns.Add(New DataColumn("Price"))
dtValues.Columns.Add(New DataColumn("Total"))
End Sub
受保护的子btnAddPurchase_Click(发件人为对象,e为EventArgs)
Dim drValues As DataRow = dtValues.NewRow()
drValues("Qty") = txtQty.Text
drValues("Materials") = txtMaterials.Text
drValues("Cost") = txtCost.Text
drValues("Price") = txtPrice.Text
dtValues.Rows.Add(drValues)
gvPurchases.DataSource = dtValues
gvPurchases.DataBind()
txtQty.Text = "1"
txtMaterials.Text = ""
txtCost.Text = "0"
txtPrice.Text = "0"
lblTotal.Text = "$0.00"
End Sub
答案 0 :(得分:0)
这种情况正在发生,因为该表仅在初始页面加载时创建,当它通过按钮单击返回时,表再次初始化但没有列,因为在Page_Load事件中IsPostBack为真。因此,通过删除IsPostBack条件,表对象将使用每个页面请求的列进行实例化。
Protected Sub Page_Load(sender As Object, e As EventArgs)
CreateDataTable()
End Sub