how to get cell value from gridview without using cell index?
Let say the first column name in my table is "RowNumber".
instead of using
string name = GridView1.Rows[0].Cells[0].Text;
Something like
string name = GridView1.Rows[0].Cells["RowNumber"].Text;
You could cast the GridViewRow's DataItem property into a DataRowView, and then reference the column names:
DataRowView rowView = (DataRowView)GridView1.Rows[0].DataItem;
string name = rowView["RowNumber"].ToString();
You can't do this from the Cells
collection, because they are just TableCell objects, and they don't know anything about the underlying data.
The DataItem property represents the values in that row from the underlying datasource, so that's what you want to deal with.
You can use datakeys to access any data you want from the row index.
In the markup of the gridview, add all the fields you want to be able to access to the gridview.
<asp:GridView ID="gvTransactionHistory" runat="server"
AutoGenerateColumns="false"
onselectedindexchanging="gvTransactionHistory_SelectedIndexChanging"
DataKeyNames="ID, AnyField">
These datakeys can be accessed in the code behind with the row index
var id = gvTransactionHistory.DataKeys[rowIndex].Values["ID"];
var AnyField = gvTransactionHistory.DataKeys[rowIndex].Values["AnyField"];
here is a function I wrote. since we typically get the same list of fields over and over again, I cached the index lookups.
private static readonly HybridDictionary cache = new HybridDictionary();
public static object[] GetColumnValues(
this GridView g,
int rownumber,
string columnNamesCommaSeparated)
{
var dataView = g.DataSource as DataView;
if (dataView != null)
{
DataRow dataRow = dataView[rownumber].Row;
object[] items = dataRow.ItemArray;
DataColumnCollection columns = dataRow.Table.Columns;
string lookupkey = g.ID + columnNamesCommaSeparated;
var colids = cache[lookupkey] as int[];
int columnCount;
if (colids == null)
{
string[] columnNames = columnNamesCommaSeparated.Split(',');
columnCount = columnNames.Count();
colids = new int[columnCount];
for (int i = 0; i < columnCount; i++)
{
colids[i] = columns.IndexOf(columnNames[i]);
}
cache.Add(lookupkey, colids);
}
columnCount = colids.Length;
var values = new object[columnCount];
for (int i = 0; i < columnCount; i++)
{
values[i] = items[colids[i]] ?? "";
}
return values;
}
return null;
}
to use it do something like
object[] values = g.GetColumnValues(e.Row.DataItemIndex, "Firstname,Lastname,CompanyName");
if (values != null)
{
string header = Server.HtmlEncode(values[0] + " " + values[1] + " @ " + values[2]);
}
// do whatever you want with this value