Getting a Value From a Datagrid

J

Juba

Hello,

I have the following code placed at my Page_Load event and after the
Datagrid is binded, so it is not empty. The problem is that the variable
isclass is always returning null and I am sure that the Category
ItemTemplate is there and that it is previouly populated. Am I missing
something? Here's the code:

private void Page_Load(object sender, System.EventArgs e)
{
if (Page.IsPostBack == false)
{

// Calculate end-user's shopping cart ID
ShoppingCartDB cart = new ShoppingCartDB();
String cartId = cart.GetShoppingCartId();

// Populate datagrid with shopping cart data
MyDataGrid.DataSource = cart.GetItems(cartId);
MyDataGrid.DataBind();

// I am trying to get the value from my ItemTemplate TextBox here:
TextBox isclass = (TextBox)MyDataGrid.FindControl("Category");

if (isclass.Text == "Classes" ) // I am sure this value is there - it is
not finding the control
{
cart.AddItem(cartId, 2, 1);
}

}
}
.....

Thanks in advance!
 
S

Scott Allen

Hi Juba:

If you are using an ItemTemplate in your grid, something like

<ItemTemplate>
<asp:TextBox Runat="server" id="mytextbox">x</asp:TextBox>
</ItemTemplate>

then click View Source in IE, you'll see ASP.NET prefixed the ID of
each textbox, something like:

<input name="DataGrid1:_ctl4:mytextbox" type="text" value="ABBA"
id="DataGrid1__ctl4_mytextbox" />

Basically, child controls receive a naming prefix from ASP.NET so it
will not render multiple TextBox controls all with the ID of
"Category".

What I have trouble understanding is this. If you have a DataGrid with
multiple rows, how do you know which one to pull data from? If you
have a "Selected" row , you can use FindControl on the parent of the
text box to find a value, i.e:

textbox = (TextBox)MyDataGrid.SelectedItem.FindControl("Category");

Using FindControl on the DataGrid will search with the proper prefix
for the control in question.

Hope this gets you started in the right direction,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top