How to Allow User to Check Only One Row at a Time in Grid View

Introduction

Most developers use a Grid View to display records.

Allowing the user to select only one row from this Grid View.

Here is an example I will show you.

  • Using JavaScript
  • Using server event

Create Table State Master

SQL Server part

CREATE TABLE [dbo].[StateMaster](

[StateID] [int] IDENTITY(1,1) primary key NOT NULL,

[StateName] [varchar](30) NULL,

[StateCode] [varchar](50) NULL,

[RecordStatus] [char](1) NULL,

)



Add Some Records



Web Forms Part

 

  • Create an ASP.NET WEBAPPLICATION
  • Add a web form
  • Name it "gridviewexample.aspx"
  • Add a Grid View to that form
  • Inside the Grid View add a column as in:
    <Columns></ Columns>
  • Inside the column add a TemplateField as in:
    <asp: TemplateField>
  • Inside the TemplateField add an Item template
  • Add a Checkbox control

 

<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">

            <Columns>

                <asp:TemplateField HeaderText ="StateName">

                    <ItemTemplate>

<asp:CheckBox ID="CheckBox1" Text='<%# Eval("StateName")%>' AutoPostBack="true"  runat="server" onclick="CheckBoxCheck(this);" />

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

 </asp:GridView>


You need to add a connection string above the Page load.

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Myconstr"].ToString());


And add a connection string in Web.config.

For making a connection with the database you need to add a connection string to the database; here is an example of that.

Just replace here with your database value.

Data source

Database

User id

Password

<connectionStrings>

    <add name="Myconstr" connectionString="data source=SAI-PC; Database=AllSampleCode;  user id=sa; password=Pass$123 ;" providerName="system.data.sqlclient"/>

  </connectionStrings>


Binding Grid View on the Page Load event.

  protected void Page_Load(object sender, EventArgs e)

    {

 

        if (!IsPostBack)

        {

            getrecords();

        }

 

    }


Now to create a method for binding records for the Grid View.

private void getrecords()

        {

 

     SqlCommand cmd = new SqlCommand("select StateID ,StateName from StateMaster ", con);

            cmd.CommandType = CommandType.Text;

            SqlDataAdapter da = new SqlDataAdapter();

            da.SelectCommand = cmd;

            DataTable dt = new DataTable();

            da.Fill(dt);

            GridView1.DataSource = dt;

            GridView1.DataBind();

 

        }


Using JavaScript (Onclick)

In the head part of the .aspx page add the following JavaScript.

To see the details, use the Firefox add-on Firebug to debug it.

<script type="text/javascript">

        function CheckBoxCheck(rb) {

            debugger;

            var gv = document.getElementById("<%=GridView1.ClientID%>");

            var chk = gv.getElementsByTagName("input");

            var row = rb.parentNode.parentNode;

            for (var i = 0; i < chk.length; i++) {

                if (chk[i].type == "checkbox") {

                    if (chk[i].checked && chk[i] != rb) {

                        chk[i].checked = false;

                        break;
                    }

                }

            }
        }    
</script>


Using Server event ( Checked Changed Event )

<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">

            <Columns>

                <asp:TemplateField HeaderText="StateName">

                    <ItemTemplate>

                        

 <asp:CheckBox ID="CheckBox1" Text='<%# Eval("StateName")%>' AutoPostBack="true" runat="server"   OnCheckedChanged="CheckBox1_CheckedChanged" />

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

        </asp:GridView>


protected void CheckBox1_CheckedChanged(object sender, EventArgs e)

        {

 

            CheckBox chk = (CheckBox)sender;

            GridViewRow gv = (GridViewRow)chk.NamingContainer;

            int rownumber = gv.RowIndex;

 

            if (chk.Checked)

            {

                int i;

                for (i = 0; i <= GridView1.Rows.Count - 1; i++)

                {

                    if (i != rownumber)

                    {

        CheckBox chkcheckbox = ((CheckBox)(GridView1.Rows[i].FindControl("CheckBox1")));

        chkcheckbox.Checked = false;

                    }

                }

            }

 

 

        }


Final output



Happy coding.

 

Next Recommended Readings