tags:

views:

60

answers:

2

In ASP.net, I'm using textbox in templatefield's itemtemplate. I got it data-bound with no problem. But my problem is, I'm trying to write a function to find column index by its data-bounding table's column name.

Something like this :

foreach (DataControlFieldCell cell in row.Cells)
{               
  if (cell.ContainingField is BoundField)
  {
    if (((BoundField)cell.ContainingField).DataField.Equals(SearchColumnName))
    {
      return columnIndex;
    }
  }
  else if (cell.ContainingField is TemplateField)
  {
    //Finding column name of data-bound textbox or dropdownlist ??
  }
}
A: 

will this helps you?

DataControlFieldCell fieldCell = HeaderRow.Cells[i] as DataControlFieldCell;

DataControlField field = fieldCell.ContainingField;

string strHdrTxt = field.HeaderText.ToString()

This one?

string colName = ds.Columns[0].ColumnName;

Bala
Thank you, Bala. But my headertext is usually different from column name.
Vachara
A: 

Here are two quick options:

Option 1

Put the column name in the SortExpression property of the TemplateField. You can then access that property to determine the column name.

if (((TemplateField)cell.ContainingField).SortExpression.Equals(SearchColumnName))
{ 
    return columnIndex; 
}

Option 2 Create a custom textbox control derived from the regular textbox control, which includes a DataField property. Set the DataField property to the column name when you declare the textbox. You can later retrieve it by using FindControl on the cell to get a reference to the textbox.

Jason Berkan