如何在按钮单击更新后选中复选框

时间:2014-08-22 07:54:55

标签: c# jquery asp.net gridview datagridview

请检查复选框后检查复选框是否在Gridview中更新相应的行。这是我的完整源代码。请帮助我在更新按钮点击后检查Gridview中的复选框。我遇到的情景是为了识别哪个用户的数据会更新。请帮助我的朋友。

    <asp:GridView ID="GridView1" runat="server" AllowPaging="True"   
            AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"  onpageindexchanging=" grvDetails_PageIndexChanging">
            <Columns>
                    <asp:TemplateField HeaderText="Page">
                         <HeaderTemplate>
                                <asp:CheckBox ID="checkAll" runat="server" onclick = "checkAll(this);"/>                               
                         </HeaderTemplate>
                         <ItemTemplate>                                
                                <asp:CheckBox ID="radID" runat="server"  onclick ="CheckSingleCheckbox(this)" />
                         </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"/>
                    <asp:BoundField DataField="FirstName"  HeaderText="FirstName"/>
                    <asp:BoundField DataField="LastName" HeaderText="LastName"/>
                    <asp:BoundField DataField="Gender" HeaderText="Gender"/>
                    <asp:BoundField DataField="Email" HeaderText="Email"/>
                    <asp:BoundField DataField="Phone" HeaderText="Phone"/>
                    <asp:BoundField DataField="ContactAddres" HeaderText="ContactAddres"/>
                    <asp:BoundField DataField="State" HeaderText="ContactState"/>
                    <asp:BoundField DataField="Country" HeaderText="ContactCountry"/>
                    <asp:BoundField DataField="CommunicationAddress" HeaderText="CommunicationAddress"/>
                    <asp:BoundField DataField="State1" HeaderText="CommunicationState"/>
                    <asp:BoundField DataField="Country1" HeaderText="CommunicationCountry"/>

                    <asp:BoundField DataField="statec" HeaderText="ContactCountry" ShowHeader="false"  />
                    <asp:BoundField DataField="countryc" HeaderText="CommunicationAddress" ShowHeader="false" />
                    <asp:BoundField DataField="CommunicationState" HeaderText="CommunicationState" ShowHeader="false"  />
                    <asp:BoundField DataField="CommunicationCountry" HeaderText="CommunicationCountry" ShowHeader="false"  />

              </Columns>
    </asp:GridView>


And this is my c# page and I'm posting code for update

    using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Collections;
namespace Reg
{
    public partial class Registration : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                gridView();
                populate1();
                populate2();
            }
        }
        public void populate1()
        {
            DataSet ds = new DataSet();
            SqlConnection con;
            SqlCommand cmd = new SqlCommand();
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
            SqlCommand com = new SqlCommand("select *from CountryDetail", con);
            SqlDataAdapter da = new SqlDataAdapter(com);
            da.Fill(ds);
            ddlCountryPermanent.DataTextField = ds.Tables[0].Columns["Country"].ToString();
            ddlCountryPermanent.DataValueField = ds.Tables[0].Columns["CID"].ToString();
            ddlCountryPermanent.DataSource = ds.Tables[0];
            ddlCountryPermanent.DataBind();
            ddlCountryPermanent.Items.Insert(0, "Select");
            ddlCountryCommunication.DataTextField = ds.Tables[0].Columns["Country"].ToString();
            ddlCountryCommunication.DataValueField = ds.Tables[0].Columns["CID"].ToString();
            ddlCountryCommunication.DataSource = ds.Tables[0];
            ddlCountryCommunication.DataBind();
            ddlCountryCommunication.Items.Insert(0, "Select");
        }
        public void populate2()
        {
            DataSet ds = new DataSet();
            SqlConnection con;
            SqlCommand cmd = new SqlCommand();
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
            SqlCommand com = new SqlCommand("select *from StatesDetail", con);
            SqlDataAdapter da = new SqlDataAdapter(com);
            da.Fill(ds);
            ddlStatePermanent.DataTextField = ds.Tables[0].Columns["State"].ToString();
            ddlStatePermanent.DataValueField = ds.Tables[0].Columns["SID"].ToString();
            ddlStatePermanent.DataSource = ds.Tables[0];
            ddlStatePermanent.DataBind();
            ddlStatePermanent.Items.Insert(0, "Select");
            ddlStateCommunication.DataTextField = ds.Tables[0].Columns["State"].ToString();
            ddlStateCommunication.DataValueField = ds.Tables[0].Columns["SID"].ToString();
            ddlStateCommunication.DataSource = ds.Tables[0];
            ddlStateCommunication.DataBind();
            ddlStateCommunication.Items.Insert(0, "Select");
        }
        protected void saveButton_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            SqlConnection con;
            SqlCommand cmd = new SqlCommand();
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
            cmd = new SqlCommand("proc_Registers", con);
            cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);
            cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);
            if (RdoGender.SelectedItem.Value == "0")
            {
                cmd.Parameters.AddWithValue("@Gender", "0");
            }
            else
            {
                cmd.Parameters.AddWithValue("@Gender", "1");
            }
            cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
            cmd.Parameters.AddWithValue("@Phone", txtPhone.Text);
            cmd.Parameters.AddWithValue("@ContactAddres", txtAddressCon.Text);
            var statcon = ddlStatePermanent.SelectedItem.Value;
            cmd.Parameters.AddWithValue("@ContactState", statcon);
            var ddlCourtyCon = ddlCountryPermanent.SelectedItem.Value;
            cmd.Parameters.AddWithValue("@ContactCountry", ddlCourtyCon);
            cmd.Parameters.AddWithValue("@CommunicationAddress", txtAddressPer.Text);
            var statper = ddlStateCommunication.SelectedItem.Value;
            cmd.Parameters.AddWithValue("@CommunicationState", statper);
            var ddlCourtyPer = ddlCountryCommunication.SelectedItem.Value;
            cmd.Parameters.AddWithValue("@CommunicationCountry", ddlCourtyPer);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            gridView();
        }
        public void gridView()
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter("proc_FinalDataGridviewNew", con);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.PageSize = 5;
            GridView1.Columns[1].Visible = true;
            GridView1.Columns[13].Visible = true;
            GridView1.Columns[14].Visible = true;
            GridView1.Columns[15].Visible = true;
            GridView1.Columns[16].Visible = true;
            Page.DataBind();
            GridView1.Columns[1].Visible = false;
            GridView1.Columns[13].Visible = false;
            GridView1.Columns[14].Visible = false;
            GridView1.Columns[15].Visible = false;
            GridView1.Columns[16].Visible = false;
        }
        protected void grvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            DataBind();
            gridView();
        }
        protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            e.Row.Cells[13].Visible = false;
            e.Row.Cells[14].Visible = false;
            e.Row.Cells[15].Visible = false;
            e.Row.Cells[16].Visible = false;
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                var chk = row.FindControl("radID") as CheckBox;
                if (chk.Checked)
                {
                    var ID = row.Cells[1].Text;
                    var fname = row.Cells[2].Text;
                    var lname = row.Cells[3].Text;
                    var gendr = row.Cells[4].Text;
                    var mail = row.Cells[5].Text;
                    var phne = row.Cells[6].Text;
                    var addrscon = row.Cells[7].Text;
                    var statecon = row.Cells[13].Text;
                    var countrycon = row.Cells[14].Text;
                    var addrsper = row.Cells[10].Text;
                    var stateper = row.Cells[15].Text;
                    var countryper = row.Cells[16].Text;
                    txtID.Text = ID;
                    txtFirstName.Text = fname;
                    txtLastName.Text = lname;
                    string gndr;
                    if (gendr == "Male")
                    {
                        gndr = "0";
                    }
                    else
                    {
                        gndr = "1";
                    }
                    RdoGender.SelectedValue = gndr;
                    txtEmail.Text = mail;
                    txtPhone.Text = phne;
                    txtAddressCon.Text = addrscon;
                    ddlStatePermanent.SelectedValue = statecon;
                    ddlCountryPermanent.SelectedValue = countrycon;
                    txtAddressPer.Text = addrsper;
                    ddlStateCommunication.SelectedValue = stateper;
                    ddlCountryCommunication.SelectedValue = countryper;
                    DataBind();
                    gridView();
                }
                else
                {
                    lblMessage.Text = "*Please select any row to Update";
                }
            }
        }

        protected void updateButton_Click(object sender, EventArgs e)
        {
            string id = txtID.Text;
            string fname = txtFirstName.Text;
            string lname = txtLastName.Text;
            string gendr = RdoGender.Text;
            string mail = txtEmail.Text;
            string phne = txtPhone.Text;
            string addrscon = txtAddressCon.Text;
            string statecon = ddlStatePermanent.SelectedItem.Value;
            string countrycon = ddlCountryPermanent.SelectedItem.Value;
            string addrsper = txtAddressCon.Text;
            string stateper = ddlStateCommunication.SelectedItem.Value;
            string countryper = ddlCountryCommunication.SelectedItem.Value;
            SqlConnection con = con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
            con.Open();
            SqlCommand cmd = new SqlCommand("proc_UpdateRegisters", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Id", id);
            cmd.Parameters.AddWithValue("@FirstName", fname);
            cmd.Parameters.AddWithValue("@LastName", lname);
            cmd.Parameters.AddWithValue("@Gender", gendr);
            cmd.Parameters.AddWithValue("@Email", mail);
            cmd.Parameters.AddWithValue("@Phone", phne);
            cmd.Parameters.AddWithValue("@ContactAddres", addrscon);
            cmd.Parameters.AddWithValue("@ContactState", statecon);
            cmd.Parameters.AddWithValue("@ContactCountry", countrycon);
            cmd.Parameters.AddWithValue("@CommunicationAddress", addrsper);
            cmd.Parameters.AddWithValue("@CommunicationState", stateper);
            cmd.Parameters.AddWithValue("@CommunicationCountry", countryper);
            cmd.ExecuteNonQuery();
            con.Close();
            GridView1.EditIndex = -1;
            DataTable dt = new DataTable();
            cmd.CommandType = CommandType.StoredProcedure;
            con.Close();
            gridView();
        }
        // row delete
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            StringCollection idCollection = new StringCollection();
            string strID = string.Empty;
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox chkDelete = (CheckBox)GridView1.Rows[i].
                                 Cells[0].FindControl("radID");
                if (chkDelete != null)
                {
                    if (chkDelete.Checked)
                    {
                        strID = GridView1.Rows[i].Cells[1].Text;
                        idCollection.Add(strID);
                    }
                }
            }
            if (idCollection.Count > 0)
            {
                DeleteMultipleRecords(idCollection);
                GridView1.DataBind();
            }
            else
            {
                lblMessage.Text = "*Please select any row to delete";
            }
            DataBind();
            gridView();
        }
        private void DeleteMultipleRecords(StringCollection idCollection)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
            SqlCommand cmd = new SqlCommand();
            string IDs = "";
            foreach (string id in idCollection)
            {
                IDs += id.ToString() + ",";
            }
            try
            {
                string test = IDs.Substring
                              (0, IDs.LastIndexOf(","));
                string sql = "Delete from Registers" + " WHERE ID in (" + test + ")";
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sql;
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                string errorMsg = "Error in Deletion";
                errorMsg += ex.Message;
                throw new Exception(errorMsg);
            }
            finally
            {
                con.Close();
            }
        }
        protected void polyuria2_CheckedChanged(object sender, EventArgs e)
        {
            if (CheckBox1.Checked == true)
            {
                var peradrs = txtAddressCon.Text;
                var stat = ddlStatePermanent.SelectedIndex;
                var contry = ddlCountryPermanent.SelectedIndex;
                txtAddressPer.Text = peradrs;
                ddlStateCommunication.SelectedIndex = stat;
                ddlCountryCommunication.SelectedIndex = contry;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这是因为ViewState无法从GridView列维护CheckBox状态。最简单的解决方案是:

添加&#39; OnCheckedChanged&#39;和&#39; OnDataBinding&#39;复选框列的事件

<ItemTemplate>
    <asp:CheckBox ID="radID" runat="server" OnCheckedChanged="radID_CheckedChanged" OnDataBinding="radID_DataBinding" />
</ItemTemplate>

下一步将实现这些事件:

protected void radID_CheckedChanged(object sender, EventArgs e)
{
    CheckBox checkbox = (CheckBox)sender;
    if (checkbox.Checked)
    {
        ViewState[checkbox.UniqueID] = true;
    }
    else
    {
        ViewState.Remove(checkbox.UniqueID);
    }
}

protected void radID_DataBinding(object sender, EventArgs e)
{
    CheckBox checkbox = (CheckBox)sender;
    checkbox.Checked = ViewState[checkbox.UniqueID] != null;
}

如果有帮助,请告诉我。

相关问题