I have a dataList with a command button, i want to click the button and obtain the value of a field in the datalist view of the button i have clicked.
I have tried various solutions but keep getting
{"Object reference not set to an instance of an object."}
here is my datalist
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1" Width="579px" OnItemCommand = "Datalist1_ItemCommand">
<ItemTemplate>
Epic:
<asp:Label ID="EpicLabel" runat="server" Text='<%# Eval("Epic") %>' />
<br />
ID:
<asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' />
<br />
Company:
<asp:Label ID="CompanyLabel" runat="server" Text='<%# Eval("Company") %>' />
<br />
Date:
<asp:Label ID="DateLabel" runat="server" Text='<%# Eval("Date") %>' />
<br />
time:
<asp:Label ID="timeLabel" runat="server" Text='<%# Eval("time") %>' />
<br />
NewsItem:
<asp:Label ID="NewsItemLabel" runat="server" Text='<%# Eval("NewsItem") %>' />
<br />
HeadLine:
<asp:Label ID="HeadLineLabel" runat="server" Text='<%# Eval("HeadLine") %>' />
<br />
<asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("Epic", "{0}") %>' Text="Button" />
<br />
</ItemTemplate>
</asp:DataList>
and her is my code behind
public void Datalist1_ItemCommand(object sender, DataListCommandEventArgs e)
{
var button = sender as Button;
/// if (button == null) return;
var dataListItem = button.NamingContainer as DataListItem;
if (dataListItem == null) return;
var currentKey = DataList1.DataKeys[dataListItem.ItemIndex];
var myLabel = button.Parent.Controls.Cast<Control>().FirstOrDefault(x => x.ID == "Epic") as Label;
/// if (myLabel == null) return;
var myLabelText = myLabel.Text;
}
If I am not mistaken, the ID of the control you are looking for is actually called
EpicLabel
, not justEpic
. IfmyLabel
is what the debugger is saying is not set to an instance of an object, this is most likely your problem.So this line:
would need to be: