C# – ASP.NET: How to get values from a selected row from GridView control

asp.netaspxgridviewcgridview

I have added a GridView control on my ASP.net webpage and data bound it to a List<> the list contains a collection of a simple custom objects which is defined as:

public class PersonRecord
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Notes { get; set; }
}

I have set AutoGenerateSelectButton to true and and attached an event handler to the SelectedIndexChanged event. I can see my event handler fires and I can get the selected row index by using MyGridView.SelectedIndex.

My question is: how do I use the selected row index to get the PersonId for the selected record?

I thought MyGridView.Rows[MyGridView.SelectedIndex].Cells[0] would do it but it doesn't because MyGridView.Rows.Count is 0.

TIA

Best Answer

Just because I have not played with web applications in awhile, I decided to see if this was something I could dupe. Alas, to no avail. This works fine for me:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            var persons = CreatePersons();
            GridView1.DataSource = persons;
            GridView1.DataBind();
        }
    }

    private List<PersonRecord> CreatePersons()
    {
        var person = new PersonRecord
                         {
                             PersonId = 1,
                             Name = "greg",
                             Title = "Supreme Coder",
                             Description = "Nada",
                             Notes = "foo bar"
                         };

        var person2 = new PersonRecord
        {
            PersonId = 2,
            Name = "Sam",
            Title = "Junior Coder",
            Description = "Nada",
            Notes = "foo bar"
        };

        var list = new List<PersonRecord> {person, person2};

        return list;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        var row = GridView1.Rows[0];
        var cell = row.Cells[1];
        var value = cell.Text;


    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = GridView1.SelectedIndex;
        var row = GridView1.Rows[index];
        var nameCell = row.Cells[2];
        var name = nameCell.Text;

        Label1.Text = name;
    }
}

Yours most likely fails as you are selecting the select column (cell[0]), but I would think you should get something out of this cell (have to play with it). It could also be a bad pattern for binding.