mardi 10 avril 2018

Not able to update database using checked rows in gridview in c# ASP.NET

I'm trying to promote students from previous class to a new one. For this I'm using a gridview with checkboxes to select the students and update only selected student details in the database with the new class. Now, the problem is that when I click promote only the first row details is getting updated to new class and the rest are not. Even though I'm using foreach so that all the selected students get updated. I'm stuck! Kindly help me..

Here is my aspx markup:

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <script type = "text/javascript">
function checkAll(objRef)
{
    var GridView = objRef.parentNode.parentNode.parentNode;
    var inputList = GridView.getElementsByTagName("input");
    for (var i=0;i<inputList.length;i++)
    {
        //Get the Cell To find out ColumnIndex
        var row = inputList[i].parentNode.parentNode;
        if(inputList[i].type == "checkbox"  && objRef != inputList[i])
        {
            if (objRef.checked)
            {
                //If the header checkbox is checked, check all checkboxes
                inputList[i].checked=true;
            }
            else
            {
                //If the header checkbox is unchecked, uncheck all checkboxes
                inputList[i].checked=false;
            }
        }
    }
}
</script>
    <script type="text/javascript">
   var TargetBaseControl = null;
        
   window.onload = function()
   {
      try
      {
         //get target base control.
         TargetBaseControl = 
           document.getElementById('<%= this.GridView1.ClientID %>');
      }
      catch(err)
      {
         TargetBaseControl = null;
      }
   }
        
   function TestCheckBox()
   {              
      if(TargetBaseControl == null) return false;
      
      //get target child control.
      var TargetChildControl = "chkPromote";
      var TargetChildControlAll = "chkboxSelectAll";
            
      //get all the control of the type INPUT in the base control.
      var Inputs = TargetBaseControl.getElementsByTagName("input"); 
            
      for(var n = 0; n < Inputs.length; ++n)
         if(Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl,0) >= 0 && Inputs[n].checked || Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControlAll, 0) >= 0 &&
            Inputs[n].checked)
          return true;        
            
      alert('Select at least one student!');
      return false;
   }
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div class="content-wrapper">
        <section class="content-header">
            <h1>Student Promotion
        <small>Administrator</small>
            </h1>
            <ol class="breadcrumb">
                <li><a href="#"><i class="fa fa-dashboard"></i>Home</a></li>
                <li class="active">Student Promotion</li>
            </ol>
        </section>
        <section class="content">
            <div class="box box-danger">
                <div class="box-header with-border">
                    <h3 class="box-title">Student Promotion Manager</h3>
                </div>
                <div class="box-body">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Select Standard You Wanna Promote</label>
                            <asp:DropDownList ID="drpclass" runat="server" CssClass="btn btn-default form-control" OnSelectedIndexChanged="drpclass_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
                        </div>
                    </div>
                    <div class="col-md-12" style="overflow: scroll; height: 200px">
                        <div class="form-group">
                            <asp:GridView ID="GridView1" runat="server" CssClass="table table-bordered table-condensed table-hover table-responsive"
                                GridLines="None">
                                <Columns>
                                    <asp:TemplateField>
                                        <HeaderTemplate>
                                            <asp:CheckBox ID="chkboxSelectAll" AutoPostBack="true" OnCheckedChanged="checkmobilenumbers"  runat="server" onclick="checkAll(this);" />
                                        </HeaderTemplate>
                                        <ItemTemplate>
                                            <asp:CheckBox ID="chkPromote" runat="server"  OnCheckedChanged="checkmobilenumbers" />
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Sl. No.">
                                        <ItemTemplate>
                                            <%#Container.DataItemIndex + 1 %>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>
                        </div>
                    </div>
                </div>
                <div class="box-footer">
                    <div class="pull-right">
                        <asp:Button ID="btnPromote" runat="server" CssClass="btn btn-default" OnClientClick="javascript:return TestCheckBox();" Text="Promote Selected Students" OnClick="PromoteSelectedStudents" />
                    </div>
                </div>
            </div>
        </section>
    </div>
</asp:Content>

And here is my c# code behind:

protected void PromoteSelectedStudents(object sender, EventArgs e)
{
    if (drpclass.SelectedIndex.ToString() != "0")
    {
        try
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                //if eligible start promote process                    
                CheckBox chkRow = (CheckBox)row.FindControl("chkPromote");
                //bool isSelected = (row.FindControl("chkPromote") as CheckBox).Checked;
                if (chkRow.Checked)
                {
                    string nowDate = DateTime.Now.AddDays(365).ToString();
                    string classdrp = drpclass.SelectedItem.ToString();
                    //Int16 clsupdt = Convert.ToInt16(classdrp + 1);
                    string Student = row.Cells[4].Text.Trim();
                    string dateCreated = DateTime.Now.ToShortDateString();
                    con.Open();
                    cmd.Connection = con;
                    cmd.CommandText = "update studentregistration set class = (Select promotable_to from addclass where classname = '" + classdrp + "'), LastPromotedOn = convert(varchar, GETDATE(), 103), NextPossiblePromotion = DATEADD(year, 1, NextPossiblePromotion) where class = '" + classdrp + "' and name = '" + Student + "'";
                    int i = cmd.ExecuteNonQuery();
                    if (i > 0)
                    {
                        message = "Selected Students are promoted to the new class & the next promotion date is: " + nowDate;
                        script += message;
                        script += "')};";
                        ClientScript.RegisterStartupScript(this.GetType(), "Message From St.Joseph", script, true);
                        ga.bindClassDropDown(drpclass);
                        GridView1.DataSource = "";
                        GridView1.DataBind();
                    }
                    con.Close();
                }

            }
        }
        catch (Exception ex)
        {
            Response.Write("<script language='javascript'>alert('" + Server.HtmlEncode(ex.Message.ToString()) + "')</script>");
        }
    }
    string strConnString = ConfigurationManager.ConnectionStrings["stjosephconnect"].ConnectionString;
}

Please go through my code and any help would be appreciated..

Aucun commentaire:

Enregistrer un commentaire