A gridview, like we all programmers know, is heavy and used for editing, paging and sorting. GridView can be accessed declaratively(in the Markup section) or programmatically(in code-behind). It is upto the developer’s choice where he wants to access Gridview from.
I prefer programmatic access, i.e, accessing the gridview from code-behind. To access the gridview control programmatically, you can see many articles, tips, tricks online. Here we are going to see a simple technique to access a gridview.
Important points to remember:
1. a gridview is made up of textboxes, meaning if a gridview row has 5 columns, it means that gridview row has 5 textboxes in it.
2. every row of gridview can be accessed as a GridViewRow thus:
GridViewRow gvr = GridView1.Rows[idx];
3. every column within a GridViewRow is accessed as a Cell thus:
int n = gvr.Cells.Count; //gives the number of cells in a gridview row.
4. To access the value stored within any cell,
TextBox t = new TextBox(); //dynamically creating a new textbox just to hold the Item’s value
t.text = gvr.Cells[idx].Text; //our new textBox holds the specific gridview cell’s value.
5. If you have set Select, Edit, Delete buttons on the gridview, gridview counts each of these as a cell and returns ” ” value. This is not what we usually expect. We expect the item’s value. So we should have the statement as,
t.text = gvr.Cells[3].Text; // Select[idx=0], Edit[idx=1], Delete[idx =2], required Item[idx=3]