Kishan Shah Kishan Shah - 1 year ago 139
ASP.NET (C#) Question

ASP.NET Find id of selected row from datalist

I have a datalist in my ASP.Net web form. The datalist has an image button and a hyperlink. These things are kept in the item template in the datalist. I want to get the id of the row in which the image is clicked. Here is my ASP.Net code

<div height="100%" width="100%" class="w3-center">
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand" OnSelectedIndexChanged="DataList1_SelectedIndexChanged1" >
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%#Eval("Image_path") %> ' CommandName="Item" CommandArguement='<%#Eval("Catg_Id") %>' Height="200" Width="350" NavigateUrl='<%#String.Concat("SelectedCatg.aspx?category=",Eval("Catg_Name")) %>'/><br />
<asp:HyperLink runat="server" NavigateUrl='<%#String.Concat("SelectedCatg.aspx?category=",Eval("Catg_Name")) %>' CssClass="link" Font-Size="18"><%#Eval("Catg_name") %></asp:HyperLink>

I have itemCommand event but it doesn't catch the event on clicking the image button.

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);

String index=e.CommandArgument.ToString();
Response.Redirect("~/SelectedCatg.aspx?id=" + index);
/* if (e.CommandName.Equals("img"))
int AnswerId = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex].ToString());


Need help.

This is how I bind my datalist

String conString = ConfigurationManager.ConnectionStrings["con"].ToString();
con = new SqlConnection(conString);
String query = "Select * from Category_Master";
cmd = new SqlCommand(query,con);
dr = cmd.ExecuteReader();
dt = new DataTable();
DataList1.DataSource = dt;

Answer Source

did you try which command was fired? check this and let me know the result please.

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
            if (e.CommandName == "Item") 

                int index= Convert.ToInt32(e.CommandArgument); 

               Response.Redirect("~/SelectedCatg.aspx?id=" + index);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download