Thomas Colbert Thomas Colbert - 10 days ago 5
ASP.NET (C#) Question

Select row in Listview selects the last row in the list view rather that the row I select

In an aspx page I have a Listview with a select button on each row. When the select button is clicked it selects that row, but it always gets the data from the last row in the listview, rather than the one Im selecting.

The controlid is a parameter for the GetDeadline method which calls a stored procedure to select the row where the controlid column equals the controlid parameter.

protected void ListView1_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
{
try
{
foreach (ListViewItem item in ListView1.Items)
{
Label mylabel = (Label)item.FindControl("ControlIDLabel");
Session["controlid"] = mylabel.Text;
}

controlid = Session["controlid"].ToString();

Deadline newdeadline = Deadline.GetDeadline(controlid);

Bind();
}
catch (Exception ex)
{
lblStatus.Text = ex.Message;
}
}


And a further example of what I mean:

ControlID | Name |
---------------------------------
1 Row One Select
2 Row Two Select
3 Row Three Select
4 Row Four Select


No matter which row I select, mylabel.Text = "4".

How can I get that to get the data from the correct row?

mww mww
Answer

You have to get selected item and in this item find your label. If you search label in loop foreach it always set to Session["controlid"] last label text as value. Try use this code.

Here you can find more about ListView.SelectedIndexChanging Event

protected void ListView1_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
        {
            try
            {
               ListViewItem item = (ListViewItem)ProductsListView.Items[e.NewSelectedIndex];
               Label mylabel = (Label)item.FindControl("ControlIDLabel");
               Session["controlid"] = mylabel.Text;


                controlid = Session["controlid"].ToString();

                Deadline newdeadline = Deadline.GetDeadline(controlid);

                Bind();
            }
            catch (Exception ex)
            {
                lblStatus.Text = ex.Message;
            }
        }
Comments