Question : Gridview get textbox value onselectedindexchanged

Hi,

I have a gridview with a textbox in a template field that I'm trying to retrieve when SelectedIndexChanged changes.

Debug says variable 'qtyText' is a blank value. Can you help, code attached?

Thanks
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
Code behind:
protected void gvCatalogueItems_SelectedIndexChanged(Object sender, EventArgs e)
        {

            GridViewRow row = gvCatalogueItems.SelectedRow;
                     
             string qtyText = ((TextBox)gvCatalogueItems.SelectedRow.FindControl("QtyToAdd")).Text;
}

GRIDVIEW:
<asp:GridView ID="gvCatalogueItems" runat="server" CellPadding="4" 
                            DataKeyNames="ID" ForeColor="#333333" GridLines="Horizontal" 
                            EmptyDataText=".. No items found in category" OnRowDataBound="CatalogueItems_RowDataBound"
                            OnSelectedIndexChanged="gvCatalogueItems_SelectedIndexChanged"
                            OnSelectedIndexChanging="gvCatalogueItems_SelectedIndexChanging">
                             <Columns>
                                <asp:CommandField ButtonType="Button" SelectText="Add" ShowSelectButton="True">
                                    <HeaderStyle Font-Names="Arial" Font-Size="10pt"  />
                                </asp:CommandField>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:TextBox ID="QtyToAdd" runat="server" Width="25px"></asp:TextBox>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                
                               
                            </Columns>
                            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                            <EditRowStyle BackColor="#999999" />
                            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                        </asp:GridView>

Answer : Gridview get textbox value onselectedindexchanged

As i have checked your code and found that you are calling your function "PopulateCatalogueItems();" in the else part of the Page.IsPostBack clause in the Page Load Event. So this is the function which is binding your gridview again with the datasource and making the text of your textbox blank.

So kindly remove that function from the else part.
You can check out my code which is almost your code but ihave changed soem where you are calling web service. ASPX Page is same as of yours.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
405:
406:
407:
408:
409:
410:
411:
412:
413:
414:
415:
416:
417:
418:
419:
420:
421:
422:
423:
424:
425:
426:
427:
428:
429:
430:
431:
432:
433:
434:
435:
436:
437:
438:
439:
440:
441:
442:
443:
444:
445:
446:
447:
448:
449:
450:
451:
452:
453:
454:
455:
456:
457:
458:
459:
460:
461:
462:
463:
464:
465:
466:
467:
468:
469:
470:
471:
472:
473:
474:
475:
476:
477:
478:
479:
480:
481:
482:
483:
484:
485:
486:
487:
488:
489:
490:
491:
492:
493:
494:
495:
496:
497:
498:
499:
500:
501:
502:
503:
504:
505:
506:
507:
508:
509:
510:
511:
512:
513:
514:
515:
516:
517:
518:
519:
520:
521:
522:
523:
524:
525:
526:
527:
528:
529:
530:
531:
532:
533:
534:
535:
536:
CODE BEHIND: 

static DataTable dt = null;
    static long itemcategory;
    static string qtyText;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            PopulateDropdown();

            PopulateCatalogueItems();

            if (Session["dtItems"] == null)
            {

                Session["counter"] = 0;  // used to increment the 'id' Datatable value

                dt = new DataTable();

                dt.Columns.Add("ID");
                dt.Columns.Add("Qty");
                dt.Columns.Add("Desc");
                dt.Columns.Add("UOI");
                dt.Columns.Add("Item");

                ItemInOrder.DataSource = dt;
                ItemInOrder.DataBind();

                lblItemsInOrder.Text = "0";

                Session["OrderedItems"] = string.Empty;
            }
            else
            {

                Session["OrderedItems"] = Session["dtItems"];

                ItemInOrder.DataSource = dt;

                ItemInOrder.DataBind();

                int @counter = Convert.ToInt32(ItemInOrder.Rows.Count);
                lblItemsInOrder.Text = @counter.ToString();

                if (@counter > 0)
                {
                    lnkCheckOutButton.Visible = true;
                }
            }

        }
        else
        {
            PopulateCatalogueItems();
        }

    }

    protected void PopulateDropdown()
    {

        // SNPWebservice2.SNPWebservice service = new SNPWebservice2.SNPWebservice();

        DataSet dsFromSOAP = new DataSet();
        DataTable tableFromSOAP = new DataTable();
        tableFromSOAP.Columns.Add("Category");
        tableFromSOAP.Columns.Add("CategoryId");
        DataRow rowTemp;

        rowTemp = tableFromSOAP.NewRow();
        rowTemp["Category"] = "ALL ITEMS";
        rowTemp["CategoryId"] = "1";
        tableFromSOAP.Rows.Add(rowTemp);
        tableFromSOAP.AcceptChanges();

        rowTemp = tableFromSOAP.NewRow();
        rowTemp["Category"] = "Books";
        rowTemp["CategoryId"] = "5";
        tableFromSOAP.Rows.Add(rowTemp);
        tableFromSOAP.AcceptChanges();

        dsFromSOAP.Tables.Add(tableFromSOAP);
        dsFromSOAP.AcceptChanges();

        // dsFromSOAP = service.ListDSCategory();

        foreach (DataRow dataRow in dsFromSOAP.Tables[0].Rows)
        {

            string category = dataRow["Category"].ToString();

            if (category != "newcat")
            {
                if (category != "Non-Stock Items")

                    ddlCategory.Items.Add(category);
            }

        }

        dsFromSOAP.Dispose();

        //int noTestsInDataset = dsFromSOAP.Tables[0].Rows.Count;

    }

    protected void PopulateCatalogueItems()
    {

        string _ddlCategory = ddlCategory.Text;

        if (_ddlCategory == "ALL ITEMS")
        {
            GetAllCatalogueItems();
        }
        else
        {

            if (_ddlCategory != "newcat")
            {

                if (_ddlCategory != "- Select Category -")
                {

                    GetCatalogueItems(_ddlCategory);

                }
            }
        }

    }

    protected void GetAllCatalogueItems()
    {

        // SNPWebservice2.SNPWebservice service = new SNPWebservice2.SNPWebservice();

        DataSet dsFromSOAP = new DataSet();
        DataTable tableFromSOAP = new DataTable();
        tableFromSOAP.Columns.Add("Category");
        tableFromSOAP.Columns.Add("Id");
        DataRow rowTemp;

        rowTemp = tableFromSOAP.NewRow();
        rowTemp["Category"] = "Catalogue 1";
        rowTemp["Id"] = "1";
        tableFromSOAP.Rows.Add(rowTemp);
        tableFromSOAP.AcceptChanges();

        rowTemp = tableFromSOAP.NewRow();
        rowTemp["Category"] = "Catalogue 2";
        rowTemp["Id"] = "5";
        tableFromSOAP.Rows.Add(rowTemp);
        tableFromSOAP.AcceptChanges();

        dsFromSOAP.Tables.Add(tableFromSOAP);
        dsFromSOAP.AcceptChanges();
        
        // dsFromSOAP = service.ListAllDSCatalogue();

        int noTestsInDataset = dsFromSOAP.Tables[0].Rows.Count;

        gvCatalogueItems.DataSource = dsFromSOAP;

        gvCatalogueItems.DataBind();

    }

    protected void GetCatalogueItems(string _category)
    {

        switch (_category)
        {
            case "Autoclave testing - Steam sterilisation":
                itemcategory = 3;
                break;
            case "Blood Collection":
                itemcategory = 4;
                break;
            case "Books":
                itemcategory = 5;
                break;
            case "Brochures":
                itemcategory = 6;
                break;
            case "Bulletin/Test Announcements":
                itemcategory = 7;
                break;
            case "Clinic Information":
                itemcategory = 8;
                break;
            case "Collection Notes":
                itemcategory = 9;
                break;
            case "Directional Maps":
                itemcategory = 10;
                break;
            case "Faeces collection":
                itemcategory = 11;
                break;
            case "General":
                itemcategory = 12;
                break;
            case "Gynaecological and cytological collection":
                itemcategory = 13;
                break;
            case "Histology and Skin pathology":
                itemcategory = 14;
                break;
            case "Microbiology collection":
                itemcategory = 15;
                break;
            case "Non-Stock Items":
                itemcategory = 16;
                break;
            case "Request Forms":
                itemcategory = 17;
                break;
            case "Stationery":
                itemcategory = 18;
                break;
            case "Urine collection":
                itemcategory = 19;
                break;
            //case "ALL ITEMS":
            //    itemcategory = 2;
            //    break;
            default:
                itemcategory = 0;
                break;
        }

        // SNPWebservice2.SNPWebservice service = new SNPWebservice2.SNPWebservice();

        DataSet dsFromSOAP = new DataSet();

        // dsFromSOAP = service.ListDSCatalogue(true, true, itemcategory, true);

        int noTestsInDataset = dsFromSOAP.Tables[0].Rows.Count;

        gvCatalogueItems.DataSource = dsFromSOAP;

        gvCatalogueItems.DataBind();

    }

    protected void ItemInOrder_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        GridViewRow deletedItem = ItemInOrder.Rows[e.RowIndex];
        lblDeleted.Text = lblDeleted.Text + "Item deleted " + deletedItem.Cells[5].Text + " - " + deletedItem.Cells[3].Text + "<br />";

        dt.Rows[e.RowIndex].Delete();

        int @counter = Convert.ToInt32(Session["counter"]) - 1;

        Session["counter"] = @counter;

        lblItemsInOrder.Text = @counter.ToString() + " - Item was deleted";
        Server.HtmlEncode(lblItemsInOrder.Text);

        ItemInOrder.DataSource = dt;
        ItemInOrder.DataBind();

        int @counter1 = Convert.ToInt32(Session["counter"]);

        if (@counter1 < 1)
        {
            lnkCheckOutButton.Visible = false;
        }

    }


    protected void gvCatalogueItems_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
    {
        if (Page.IsPostBack)
        {

            GridViewRow row = gvCatalogueItems.Rows[e.NewSelectedIndex];

            TextBox txt = (TextBox)gvCatalogueItems.Rows[e.NewSelectedIndex].FindControl("QtyToAdd");

            if (txt != null)
            {
                string value = txt.Text.ToString();
            }

        }
    }


    protected void gvCatalogueItems_SelectedIndexChanged(Object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {

            //GridViewRow row = gvCatalogueItems.SelectedRow;

            //if (((TextBox)gvCatalogueItems.SelectedRow.FindControl("QtyToAdd")).Text != null)
            //{
            //    string qtyText = ((TextBox)gvCatalogueItems.SelectedRow.FindControl("QtyToAdd")).Text;

            //}


            //int maxOrderQty = Convert.ToInt32(row.Cells[7].Text);

            //try
            //{
            //    int orderQty = Convert.ToInt32(qtyText);

            //    if (orderQty > maxOrderQty)
            //    {
            //        Response.Write("<script>alert('Quantity you ordered exceeds the maximum order quantity for this item.')</script>");
            //        return;
            //    }

            //}
            //catch
            //{
            //    Response.Write("<script>alert('Quantity is Blank or non-numeric, Click Cancel to go back.')</script>");
            //    return;
            //}

            //DataRow dr = dt.NewRow();

            //int @counter = Convert.ToInt32(Session["counter"]) + 1;

            //dr["ID"] = @counter;
            //dr["Qty"] = qtyText;
            //dr["Desc"] = row.Cells[3].Text;
            //dr["UOI"] = row.Cells[4].Text;
            //dr["Item"] = row.Cells[9].Text;

            //dt.Rows.Add(dr);

            //ItemInOrder.DataSource = dt;
            //ItemInOrder.DataBind();

            //Session["counter"] = @counter;

            //Session["OrderedItems"] = Session["OrderedItems"] + " " + qtyText + " " +
            //    row.Cells[3].Text + " " + row.Cells[4].Text + " " + row.Cells[5].Text + "<br />";

            //lblItemsInOrder.Text = @counter.ToString() + ", Last Item - " + row.Cells[4].Text;
            //Server.HtmlEncode(lblItemsInOrder.Text);

            //lnkCheckOutButton.Visible = true;
        }

    }


    protected void btnSelect_Click(object sender, EventArgs e)
    {
        LinkButton btnSelect = sender as LinkButton;

        GridViewRow gvr = btnSelect.NamingContainer as GridViewRow;

        string _imageURL = string.Concat("picpage.aspx?imageURL=", gvCatalogueItems.DataKeys[gvr.RowIndex]["Item_Image"].ToString());

        string winFeatures = "toolbar=no,status=no,menubar=no,location=center,scrollbars=yes,resizable=yes,height=300,width=400";
        ClientScript.RegisterStartupScript(this.GetType(), "newWindow", String.Format("<script type='text/javascript'>window.open('{0}', 'yourWin', '{1}');</script>", _imageURL, winFeatures));

    }


    protected void lnkCheckOut_Click(object sender, EventArgs e)
    {

        Session["dtItems"] = dt;

        Response.Redirect("OrderSummary.aspx");

    }

    private void CreateOrder()
    {

        string username = Request.QueryString["UserName"];

        ////Define Data Objects

        //SqlConnection conn;
        //SqlCommand comm;

        ////Read the connection string from web.config

        //string connectionString =
        //    ConfigurationManager.ConnectionStrings[
        //    "docstoresConnectionString"].ConnectionString;

        //foreach (DataRow row in dt.Rows)
        //{

        //    //Initialize Connection

        //    conn = new SqlConnection(connectionString);

        //    //Create Command

        //    comm = new SqlCommand(
        //        "INSERT INTO WebOrders(Username,Qty,Description,UOI,ItemNo)" +
        //        " VALUES (@Username,@Qty,@Description,@UOI,@ItemNo)", conn);

        //    comm.Parameters.Add("@Username", SqlDbType.NVarChar);
        //    comm.Parameters["@Username"].Value = username;

        //    comm.Parameters.Add("@Qty", SqlDbType.Int);
        //    comm.Parameters["@Qty"].Value = (string)row["Qty"];

        //    comm.Parameters.Add("@Description", SqlDbType.NVarChar);
        //    comm.Parameters["@Description"].Value = (string)row["Desc"];

        //    comm.Parameters.Add("@UOI", SqlDbType.NVarChar);
        //    comm.Parameters["@UOI"].Value = (string)row["UOI"];

        //    comm.Parameters.Add("@ItemNo", SqlDbType.VarChar);
        //    comm.Parameters["@ItemNo"].Value = (string)row["Item"];

        //    // Enclose database code in Try-Catch-Finally

        //    try
        //    {
        //        // Open the connection
        //        conn.Open();
        //        // Execute the command
        //        comm.ExecuteNonQuery();

        //    }
        //    finally
        //    {
        //        // Close the connection
        //        conn.Close();

        //    }
        //}

        string redirectURL = "OrderSummary.aspx?OrderSubmitted=OK&UserName=" + username;

        //Response.Redirect(redirectURL);

    }

    protected void ItemsInOrder_RowDataBound(object s, GridViewRowEventArgs e)
    {
        // Hide the header of the leftmost column.
        //if (e.Row.RowType == DataControlRowType.Header)
        //{
        //    e.Row.Cells[6].Visible = false;
        //    e.Row.Cells[8].Visible = false;
        //    e.Row.Cells[9].Visible = false;
        //}

        //// Hide the leftmost column of the data row.
        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{

        //    string imagetext = e.Row.Cells[5].Text.Trim();

        //    if (imagetext.Contains(".jpg"))
        //    {
        //        e.Row.Cells[5].Text = "<a href=picpage.aspx?imageURL=" + e.Row.Cells[5].Text + ">Image</a>";
        //    }

        //    e.Row.Cells[6].Visible = false;
        //    e.Row.Cells[8].Visible = false;
        //    e.Row.Cells[9].Visible = false;
        //}
    }


    protected void CatalogueItems_RowDataBound(object s, GridViewRowEventArgs e)
    {
        // Hide the header of the leftmost column.
        //if (e.Row.RowType == DataControlRowType.Header)
        //{

        //    e.Row.Cells[3].Text = "Item";
        //    e.Row.Cells[4].Text = "UOI";
        //    e.Row.Cells[5].Text = "Image";
        //    e.Row.Cells[7].Text = "Max Qty";

        //    e.Row.Cells[2].Visible = false;
        //    e.Row.Cells[6].Visible = false;
        //    e.Row.Cells[8].Visible = false;
        //    e.Row.Cells[9].Visible = false;
        //    e.Row.Cells[10].Visible = false;
        //}

        ////// Hide the leftmost column of the data row.
        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{

        //    CheckBox isActive = (CheckBox)e.Row.Cells[6].Controls[0];

        //    if (isActive.Checked)
        //    {

        //        string imagetext = e.Row.Cells[5].Text.Trim();

        //        if (imagetext.Contains(".jpg"))
        //        {


        //            e.Row.Cells[5].Text = @"<a href=picpage.aspx?imageURL=" + e.Row.Cells[5].Text + "&ItemDesc=" + Server.UrlEncode(e.Row.Cells[3].Text) + " target=_blank>Image</a>";
        //        }

        //        e.Row.Cells[2].Visible = false;
        //        e.Row.Cells[6].Visible = false;
        //        e.Row.Cells[8].Visible = false;
        //        e.Row.Cells[9].Visible = false;
        //        e.Row.Cells[10].Visible = false;
        //    }
        //    else
        //    {

        //        for (int i = 0; i < 10; i++)
        //        {
        //            e.Row.Cells[i].Visible = false;
        //        }
        //    }
        //}
    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        Session["dtItems"] = dt;

        Response.Redirect("OrderSummary.aspx");
    }
Random Solutions  
 
programming4us programming4us