Joe Tyman
Joe Tyman

Reputation: 1417

How to access a dynamically created control's value in a gridview in ASP.NET

I can't figure out how to access the value of a control in a dynamically-created gridview. Thhe problem is that I don't know the name of the control. If I knew the name of the control I could do just do this :

string dropDownListText =((DropDownList).row.FindControl("DropDownList1")).SelectedItem.Value;`

I know the type of control and I know the cell it is in. Is there any way using the information about the control I have to be able to access the control's value?

Upvotes: 0

Views: 2630

Answers (3)

Jacob O'Brien
Jacob O'Brien

Reputation: 723

I have had the same problem. Add a command name to your field like CommandName="ProjectClick". Then add a rowcommand and in the row command do this:

if (e.CommandName.Equals("ProjectClick")) {
}

or you can use the text:

if (e.CommandName.Equals("")) {
    if (((System.Web.UI.WebControls.LinkButton)(e.CommandSource)).Text.Equals("Projects")) {
    }
}

Upvotes: 0

Tim B James
Tim B James

Reputation: 20364

If you know what cell it is, then you could do something like this;

TableCell tc = GridView1.Cells[indexOfCell]; 
// where GridView1 is the id of your GridView and indexOfCell is your index
foreach ( Control c in tc.Controls ){
    if ( c is YourControlTypeThatYouKnow ){
        YourControlTypeThatYouKnow myControl = (YourControlTypeThatYouKnow)c;
    }
}

If you don't know what cell it is exactly, then you can always loop through each cell. I am sure there is a better way in Linq.

With Linq (I think this should work)

var controls = GridView1.Cells[indexOfCell].Cast<Control>();
YourControlTypeThatYouKnow myControl = (YourControlTypeThatYouKnow) controls.Where( x => x is YourControlTypeThatYouKnow).FirstOrDefault();

Upvotes: 2

rt2800
rt2800

Reputation: 3045

On ItemDataBound event handler of GridView, access the table-cell as follows. Within the cell, Controls collection provides you access to ASP control embedded in the cell

TableCell cell = e.Item.Cells[0];
if (cell.Controls.Count > 0)
{
   cell.Controls[0].Visible = false;
}

Upvotes: 0

Related Questions