access table cell by name not by index?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a dynamic datagrid in which the number of columns of not fixed, the
number of columns is selected from a dropdown.

I have one column header called "Brand/Model" and on the onItemDataBound i
want to modify the values relates to this column.. the problem is because the
index value is not fixed i can't use .. e.Item.Cells[int].Text

My question is how can i reference the cell by the cloumn header "BrandModel"?
is there a another way this solve this?

many thanks in advance..
 
Huzz,

Never access a datagrid using the grid itself, access it by using the
datasource of it.

I hope this helps?

Cor
 
Cor thanks for your reply..
I don't know how to access it by datasource.. can you show me what code i
need to write.. or any good article?

many thanks
 
Huzz,

I made this sample the day before yesterday however the OP did not give any
reaction on this.
However maybe it is now helpfull for you.

The only thing you have to do for it is drag a datagrid and a button on a
form paste this code bellow in, set the events in the code and run.

private void button1_Click(object sender, System.EventArgs e)
{
DataView dv = (DataView)this.dataGrid1.DataSource;
DataTable dt = dv.Table;
DataRow dr = dt.NewRow();
dr.ItemArray = new object[] {2,"002","Thee - Ceylon"};
dt.Rows.Add(dr);
int i = 0;

if ((string)dv.Sort == "[ItemId]") {i = dv.Find("002");}
else if (dv.Sort == "[Quantity]") {i = dv.Find(2);}
else if (dv.Sort == "[ItemName]") {i = dv.Find("Thee - Ceylon");}
this.dataGrid1.Select(i);
}
private void FormLoad(object sender, System.EventArgs e)

{
DataTable dt = new DataTable();
dt.Columns.Add("Quantity");
dt.Columns.Add("ItemID");
dt.Columns.Add("ItemName");

for (int i = 0; i < 3; i++) {
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);}

dt.Rows[0].ItemArray = new object[] {3,"001","Coffee - Black"};
dt.Rows[1].ItemArray = new object[] {1,"015", "Donut - Boston Creme"};
dt.Rows[2].ItemArray = new object[] {1,"005","Donut - Plain"};
DataView dv = new DataView(dt);
this.dataGrid1.DataSource = dv;
}

}

I hope this helps?

Cor
 
Since you know the name of the column you could iterate through the
column names and grab the index of the desired column. Here's an
example that just spits out the column names and their index.:


private void dg1_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
ListItemType itemType = (ListItemType)e.Item.ItemType;
if(itemType == ListItemType.Header)
{
for(int i = 0; i < dg1.Columns.Count; i++)
{
Response.Write("Column Text = " + dg1.Columns.HeaderText.ToString()
+ " - Index = " + i.ToString() + "<br>");
}
}
}
 
Sorry. I guess that I click the wrong "Reply" link. I just meant to
offer huzz another alternative.
 
Back
Top