Unable to retrieve textbox value from datagrid

J

John Dalberg

I have a datagrid plus a button to save the contents of the grid to the
database. My code gets blanks in the textbox field. I am not sure why.
Also I don't know why dgi.Cells[1].Controls[0] & dgi.Cells[1].Controls[2]
are Literal Controls. The html shows only a textbox in the second table
cell.

This is the code and below is the grid.

Code:
private void btnSave_Click(object sender, System.EventArgs e)
{
string sName;
int iCPID;
foreach(DataGridItem dgi in this.dgRegister.Items)
{
if(dgi.ItemType.ToString() == "Item" || dgi.ItemType.ToString() ==
"AlternatingItem")
{

TableCell tc = (TableCell)dgi.Cells[2];
iCPID = Convert.ToInt32(tc.Text);
TextBox tb = (TextBox)dgi.Cells[1].Controls[1];


sName = tb.Text; <-- always blank!
cProfitCash.UpdateDatabase(iCPID, sName );
}
}


Grid:
<asp:datagrid id=dgRegister runat="server" AutoGenerateColumns="False">
<AlternatingItemStyle CssClass="DataGridAltItem">
</AlternatingItemStyle>

<ItemStyle CssClass="DataGridItem">
</ItemStyle>

<HeaderStyle CssClass="grid-header">
</HeaderStyle>

<Columns>
<asp:BoundColumn DataField="CPCode" ReadOnly="True"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="Name">
<HeaderStyle Font-Bold="True">
</HeaderStyle>

<ItemTemplate>

<asp:TextBox id="EmpName" Text='<%# DataBinder.Eval(Container.DataItem,
"EmpName") %>' Width="194px" runat="server"></asp:textbox>

</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn Visible="False" DataField="CPID"></asp:BoundColumn>
</Columns>
</asp:datagrid>

Jon Dalberg
 
K

Karl

My guess is because you are rebinding the datagrid on postback, wrap your
databinding code in a if (!Page.IsPostBack){ }

[0] and [2] show up as literals because you have spaces/newlines.

You should consider two other things:
Change -->
if(dgi.ItemType.ToString() == "Item" || dgi.ItemType.ToString()
=="AlternatingItem") {

to -->
if(dgi.ItemType == ListItemType.Item || dgi.ItemType ==
ListItemType.AlternatingItem) {

Why ToString() an enum for comparison purposes? its much slower and error
prone.


And, instead of accessing controls via indexes like
dgi.Cells[1].Controls[0], consider doing a FindControl() instead...it might
be slower but (a) its considerably more readable and less error prone.

For example, replace -->
TextBox tb = (TextBox)dgi.Cells[1].Controls[1];

with -->
TextBox tb = (TextBox)dgi.FindControl("EmpName");

Karl
 

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

Members online

No members online now.

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,831
Latest member
HealthSmartketoReviews

Latest Threads

Top