Reputation: 75
I am using datalist to show product id, name and a textbox("Qty") allow user to input order Qty. I got System.NullReferenceException: Object reference not set to an instance of an object error when user click an item to order. My datasource provides only 2 columns (product id and name). I added a textbox("Qty") and a button to the datalist. I can not get the value from the textbox("Qty") to submit. Could it be my datasource does not contain the "Qty" column thus FindControl alway return null value? How do I fix the problem? Thanks. Here is my code:
<asp:DataList ID="DataList1" runat="server" CellPadding="10" DataKeyField="product_id" DataSourceID="SqlDataSource1" RepeatColumns="2">
<ItemTemplate>
<asp:Label ID="product_id" runat="server"
Text='<%# Eval("product_id") %>' /><br/>
<asp:Label ID="product_name" runat="server"
Text='<%# Eval("product_name") %>' />
<br />
<asp:TextBox ID="Qty" runat="server"></asp:TextBox>
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to Cart" CommandName="addtocart2" OnCommand="DataList1_ItemCommand"
/>
</ItemTemplate>
</asp:DataList>
Here is the code for the button:
public void DataList1_ItemCommand(object source, System.Web.UI.WebControls.CommandEventArgs e)
{
var qtytxtbox = DataList1.FindControl("Qty") as TextBox;
// qtytxtbox always return null, why?
}
Upvotes: 1
Views: 10834
Reputation: 40970
Your handler doesn't look correct. you should use DataListCommandEventArgs
as second parameter. so try something like this
Markup:
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand" vCellPadding="10" DataKeyField="product_id" DataSourceID="SqlDataSource1" RepeatColumns="2">
Then Add command name in button
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to Cart" CommandName="addtocart2" />
and code behind
public void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if(e.CommandName.Equals("addtocart2")
{
TextBox qtytxtbox = (TextBox)(e.Item.FindControl("Qty"));
}
}
Upvotes: 0