Uncheck ASP.Net GridView Rows based on condition using C# and VB.Net

Last Reply 3 months ago By pandeyism

Posted 3 months ago

I have a grid view with some fields. and I want to uncheck a row of gridview with som conditions:

this is my gridviewcode:

       <asp:GridView ID="GridView1" runat="server" EmptyDataText="هیچ واحدی تعریف نشده است"  AutoGenerateColumns="False" Width="932px" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" Font-Names="Tahoma">
                         <Columns>
                             <asp:TemplateField HeaderText="select">
                                 <ItemTemplate>
                                     <asp:CheckBox ID="chkSelect" runat="server" Checked='<%# Convert.ToBoolean(Eval("IsChecked").ToString()) %>'
                                         OnCheckedChanged="OnCheckedChanged" AutoPostBack="true" />
                                 </ItemTemplate>
                             </asp:TemplateField>
                          

                               <asp:BoundField DataField="TRoom" HeaderText="RoomTitle "  HeaderStyle-CssClass="header-center" />
                             <asp:BoundField DataField="DayWeek" HeaderText="DayWeek "  HeaderStyle-CssClass="header-center" />
                             <asp:BoundField DataField="ET" HeaderText="EndTime  "  HeaderStyle-CssClass="header-center" />
                             <asp:BoundField DataField="ST" HeaderText="  StartTime"   HeaderStyle-CssClass="header-center"/>
                             <asp:BoundField DataField="LNProfessor" HeaderText="  ProfessorLastName"  HeaderStyle-CssClass="header-center" />
                             <asp:BoundField DataField="NProfessor" HeaderText=" ProfessorName"  HeaderStyle-CssClass="header-center" />
                             <asp:BoundField DataField="Code" HeaderText="LessonCode "   HeaderStyle-CssClass="header-center"/>
                             <asp:BoundField DataField="TLesson" HeaderText="LessonTitle"   HeaderStyle-CssClass="header-center"/>

                         </Columns>
                         <FooterStyle BackColor="White" ForeColor="#000066" />
                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
                         <RowStyle ForeColor="#000066" />
                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
                         <SortedAscendingCellStyle BackColor="#F1F1F1" />
                         <SortedAscendingHeaderStyle BackColor="#007DBB" />
                         <SortedDescendingCellStyle BackColor="#CAC9C9" />
                         <SortedDescendingHeaderStyle BackColor="#00547E" />
                     </asp:GridView>

and this is the data of my gridview:

now I want when the user selected the lesson title mathematical1 if the professor name of that rows does not equal then uncheck the checkbox automatically. and if users check the mathematical1 more than once, if the professor name was equaled, there was no problem.

and this is my code that do  uncheck the checkbox control:

 

 

 protected void OnCheckedChanged(object sender, EventArgs e)
        {
            GridViewRow selectedRow = (sender as CheckBox).NamingContainer as GridViewRow;
            string selectedName = selectedRow.Cells[8].Text;
            int index = selectedRow.RowIndex;
            if (ViewState["Data"] != null)
            {
                DataTable dt = ViewState["Data"] as DataTable;
                dt.Rows[index]["IsChecked"] = (sender as CheckBox).Checked;
                if ((sender as CheckBox).Checked)
                {
                    int duplicateCount = dt.Select("TLesson='" + selectedName + "'").Length;
                    if (duplicateCount > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (i != index)
                            {
                                if (dt.Rows[i]["TLesson"].ToString() == selectedName)
                                {
                                    dt.Rows[i]["IsChecked"] = false;
                                }
                            }
                        }
                    }
                }
                ViewState["Data"] = dt;
            }
            BindGridView();
        }

but it just uncheck the field with equal lesson title.

how can i do this?!

Posted 3 months ago Modified on 3 months ago

Hey dorsa,

Please refer below sample.

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:TemplateField HeaderText="select">
            <ItemTemplate>
                <asp:CheckBox ID="chkSelect" runat="server" OnCheckedChanged="OnCheckedChanged" AutoPostBack="true" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="RoomTitle" HeaderText="RoomTitle" />
        <asp:BoundField DataField="DayWeek" HeaderText="DayWeek" />
        <asp:BoundField DataField="EndDate" HeaderText="EndTime" />
        <asp:BoundField DataField="StartDate" HeaderText="  StartTime" />
        <asp:BoundField DataField="ProfessorLastName" HeaderText="ProfessorLastName" />
        <asp:BoundField DataField="ProfessorFirstName" HeaderText="ProfessorName" />
        <asp:BoundField DataField="LessonCode" HeaderText="LessonCode" />
        <asp:BoundField DataField="LessonTitle" HeaderText="LessonTitle" />
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Data;

VB.Net

Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.GridView1.DataSource = GetData();
        this.GridView1.DataBind();
    }
}

private DataTable GetData()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] { 
                        new DataColumn("LessonTitle", typeof(string)),
                        new DataColumn("LessonCode", typeof(string)), 
                        new DataColumn("ProfessorFirstName", typeof(string)), 
                        new DataColumn("ProfessorLastName", typeof(string)), 
                        new DataColumn("StartDate", typeof(string)), 
                        new DataColumn("EndDate", typeof(string)), 
                        new DataColumn("DayWeek", typeof(string)),
                        new DataColumn("RoomTitle", typeof(string)) });
    dt.Rows.Add("mathematical1", "962001", "john", "leni", "10:00:00", "11:30:00", "Saturday", "201");
    dt.Rows.Add("mathematical1", "962001", "john", "leni", "09:00:00", "10:30:00", "Sunday", "201");
    dt.Rows.Add("mathematical1", "962001", "john", "leni", "11:00:00", "12:30:00", "Monday", "201");
    dt.Rows.Add("mathematical1", "962216", "ali", "brn", "14:00:00", "16:30:00", "Saturday", "202");
    dt.Rows.Add("mathematical1", "962216", "ali", "brn", "16:30:00", "18:00:00", "Tuesday", "301");
    dt.Rows.Add("operating System", "962101", "sara", "kan", "08:00:00", "09:00:00", "Tuesday", "301");

    return dt;
}

protected void OnCheckedChanged(object sender, EventArgs e)
{
    GridViewRow selectedRow = (sender as CheckBox).NamingContainer as GridViewRow;
    string lessionName = selectedRow.Cells[8].Text;
    string firstName = selectedRow.Cells[6].Text;
    if ((sender as CheckBox).Checked)
    {
        DataRow[] dr = GetData().Select("ProfessorFirstName='" + firstName + "' AND LessonTitle = '" + lessionName + "'");
        if (dr.Length > 1)
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                string lession = row.Cells[8].Text;
                string name = row.Cells[6].Text;
                if (lessionName.ToLower().Trim() == lession.ToLower().Trim() && firstName.ToLower().Trim() == name.ToLower().Trim())
                {
                    (row.FindControl("chkSelect") as CheckBox).Checked = true;
                }
            }
        }
        else
        {
            (sender as CheckBox).Checked = false;
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.GridView1.DataSource = GetData()
        Me.GridView1.DataBind()
    End If
End Sub

Private Function GetData() As DataTable
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("LessonTitle", GetType(String)), New DataColumn("LessonCode", GetType(String)), New DataColumn("ProfessorFirstName", GetType(String)), New DataColumn("ProfessorLastName", GetType(String)), New DataColumn("StartDate", GetType(String)), New DataColumn("EndDate", GetType(String)), New DataColumn("DayWeek", GetType(String)), New DataColumn("RoomTitle", GetType(String))})
    dt.Rows.Add("mathematical1", "962001", "john", "leni", "10:00:00", "11:30:00", "Saturday", "201")
    dt.Rows.Add("mathematical1", "962001", "john", "leni", "09:00:00", "10:30:00", "Sunday", "201")
    dt.Rows.Add("mathematical1", "962001", "john", "leni", "11:00:00", "12:30:00", "Monday", "201")
    dt.Rows.Add("mathematical1", "962216", "ali", "brn", "14:00:00", "16:30:00", "Saturday", "202")
    dt.Rows.Add("mathematical1", "962216", "ali", "brn", "16:30:00", "18:00:00", "Tuesday", "301")
    dt.Rows.Add("operating System", "962101", "sara", "kan", "08:00:00", "09:00:00", "Tuesday", "301")
    Return dt
End Function

Protected Sub OnCheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim selectedRow As GridViewRow = TryCast((TryCast(sender, CheckBox)).NamingContainer, GridViewRow)
    Dim lessionName As String = selectedRow.Cells(8).Text
    Dim firstName As String = selectedRow.Cells(6).Text
    If (TryCast(sender, CheckBox)).Checked Then
        Dim dr As DataRow() = GetData().[Select]("ProfessorFirstName='" & firstName & "' AND LessonTitle = '" & lessionName & "'")
        If dr.Length > 1 Then
            For Each row As GridViewRow In GridView1.Rows
                Dim lession As String = row.Cells(8).Text
                Dim name As String = row.Cells(6).Text
                If lessionName.ToLower().Trim() = lession.ToLower().Trim() AndAlso firstName.ToLower().Trim() = name.ToLower().Trim() Then
                    TryCast(row.FindControl("chkSelect"), CheckBox).Checked = True
                End If
            Next
        Else
            TryCast(sender, CheckBox).Checked = False
        End If
    End If
End Sub

Screenshot