0

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?

2
  • 1
    Could you assign a value to the ID property when the control is dynamically created? Commented May 3, 2012 at 15:48
  • can you share the event and code the dynamically generated control ? It will be easy to check. Did you check the View Source Code after the PostBack for this dynamically created control. As per my understanding, it should be lost during PostBack. All the Dynamically/Compile time generated Controls will be Disposed by End of the Page Life Cycle. Commented May 3, 2012 at 16:10

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

0

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")) {
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.