Update ASP.Net GridView cell based on DropDownList selection using jQuery with C# and VB.Net

Last Reply 3 months ago By pandeyism

Posted 3 months ago

I have a gridview that two fields of that are updatable by jquery. one of that field is a dropdown list with two value. now I want to insert three value on dropdownlist.how can I edit my code?! 

this is my code:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('[id*=GridView1] tr td').on('click', function () {
                $('[id*=GridView1] tr td').each(function () {
                    if ($(this).index() <= 1) {
                        $(this).find('span').show();
                        $(this).find('select').hide();
                        $(this).find('input[type=text]').hide();
                        $(this).find('span').html($(this).find('input[type=text]').val());
                    }
                });
                var val = $(this).find('span').html();
                $(this).find('span').hide();
                $(this).find('select').show();
                $(this).find('input[type=text]').val(val);
                $(this).find('input[type=text]').show();
                $(this).find('input[type=text]').focus();
            });

            $("[id*=DropDownList1]").on('change', function () {
                var status = $(this).val();
                if (status != "") {
                    $(this).closest('tr').find('[id*=lblStatus]').html(status >= 1 ? "حاضر" : "غایب");
                    $(this).closest('tr').find('[id*=hfStatus]').val(status);
                }
            });
        });
    </script>

 

            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3"
                DataSourceID="SqlDataSrcAddMark" HorizontalAlign="Center" Font-Names="Tahoma" Width="729px">
                <Columns>
                    <asp:TemplateField HeaderText="وضعیت حضور جلسه امتحان" SortExpression="AttendanceStatus" ItemStyle-Width="200px" HeaderStyle-CssClass="Header-center">
                        <ItemTemplate>
                            <asp:HiddenField runat="server" ID="hfStatus" Value='<%# Eval("ExamAttendanceTypeId") %>' />
                            <asp:Label ID="lblStatus" runat="server" Text='<%# Eval("ExamAttendanceTypeId").ToString() == "False" ? "Absent" : "present" %>' ></asp:Label>
                            <asp:DropDownList ID="DropDownList1" runat="server">
                                <asp:ListItem Value="1">Present</asp:ListItem>
                                <asp:ListItem Value="2">Absent</asp:ListItem>
                                <asp:ListItem Value="3">Unauthorized absent</asp:ListItem>
                            </asp:DropDownList>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="نمره" SortExpression="Mark" ItemStyle-Width="200px" HeaderStyle-CssClass="Header-center">
                        <ItemTemplate>
                            <asp:Label ID="lbl_Text1" runat="server" Text='<%# Bind("Mark") %>'></asp:Label>
                            <asp:TextBox ID="txt_Text1" runat="server" Text='<%# Bind("Mark") %>' CssClass="hideControl"
                                AutoPostBack="true" OnTextChanged="Change"></asp:TextBox>
                        </ItemTemplate>
                        <HeaderStyle CssClass="Header-center" />
                    </asp:TemplateField>
                    <asp:BoundField DataField="LastName" HeaderText="نام خانوادگی" SortExpression="LastName" HeaderStyle-CssClass="Header-center">
                        <HeaderStyle CssClass="Header-center"></HeaderStyle>
                    </asp:BoundField>
                    <asp:BoundField DataField="FirstName" HeaderText="نام " SortExpression="FirstName" HeaderStyle-CssClass="Header-center">
                        <HeaderStyle CssClass="Header-center"></HeaderStyle>
                    </asp:BoundField>
                    <asp:BoundField DataField="SubjectStudyLessonCourseId" HeaderText="-----" SortExpression="SubjectStudyLessonCourseId" HeaderStyle-CssClass="Header-center">
                        <HeaderStyle CssClass="Header-center"></HeaderStyle>
                    </asp:BoundField>
                </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>

 

      protected void Change(object sender, EventArgs e)
        {
            TextBox txtMark = sender as TextBox;
            GridViewRow row = (GridViewRow)txtMark.NamingContainer;
            string status = (row.FindControl("hfStatus") as HiddenField).Value.Trim();
            string query = "UPDATE EDU_Student_Course_Registration SET Mark = @Mark WHERE SubjectStudyLessonCourseId = @SubjectStudyLessonCourseId";
            string constr = ConfigurationManager.ConnectionStrings["KDUIS-v1ConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    cmd.Parameters.AddWithValue("@Mark", txtMark.Text);
                    //cmd.Parameters.AddWithValue("@Status", status);
                    cmd.Parameters.AddWithValue("@SubjectStudyLessonCourseId", row.Cells[4].Text);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
           
        }

I don't know how can I change these conditions:

$("[id*=DropDownList1]").on('change', function () {
    var status = $(this).val();
    if (status != "") {
        $(this).closest('tr').find('[id*=lblStatus]').html(status >= 1 ? "Present" : "Absent");
        $(this).closest('tr').find('[id*=hfStatus]').val(status);
    }
});

 

<asp:Label ID="lblStatus" runat="server" Text='<%# Eval("ExamAttendanceTypeId").ToString() == "False" ? "Absent" : "Present" %>' ></asp:Label>

 

Posted 3 months ago Modified on 3 months ago

Hi dorsa,

Refer below sample.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .hideControl
        {
            display: none;
        }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('[id*=GridView1] tr td').on('click', function () {
                if ($(this).index() > 1) {
                    $('[id*=GridView1] tr td').each(function () {
                        if ($(this).index() > 1) {
                            $(this).find('span').show();
                            $(this).find('select').hide();
                            $(this).find('input[type=text]').hide();
                            $(this).find('span').html($(this).find('input[type=text]').val());
                        }
                    });
                    var val = $(this).find('span').html();
                    $(this).find('span').hide();
                    $(this).find('select').show();
                    $(this).find('input[type=text]').val(val);
                    $(this).find('input[type=text]').show();
                    $(this).find('input[type=text]').focus();
                }
            });

            $("[id*=DropDownList1]").on('change', function () {
                var status = $(this).val();
                if (status == "1") {
                    $(this).closest('tr').find('[id*=lblStatus]').html("Present");
                    $(this).closest('tr').find('[id*=hfStatus]').val(status);
                }
                else if (status == "2") {
                    $(this).closest('tr').find('[id*=lblStatus]').html("acceptable Absent");
                    $(this).closest('tr').find('[id*=hfStatus]').val(status);
                }
                else {
                    $(this).closest('tr').find('[id*=lblStatus]').html("unaccsebtable Absen");
                    $(this).closest('tr').find('[id*=hfStatus]').val(status);
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
            OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
                <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
                <asp:BoundField DataField="StudentId" HeaderText="StudentId" SortExpression="StudentId" />
                <asp:TemplateField HeaderText="AttendanceStatus" SortExpression="AttendanceStatus">
                    <ItemTemplate>
                        <asp:HiddenField runat="server" ID="hfStatus" Value='<%# Eval("AttendanceStatus") %>' />
                        <asp:Label ID="lblStatus" runat="server" Text='<%# Eval("AttendanceStatus")%>'></asp:Label>
                        <asp:DropDownList ID="DropDownList1" runat="server" CssClass="hideControl">
                            <asp:ListItem Value="">Select</asp:ListItem>
                            <asp:ListItem Value="2">acceptable Absent</asp:ListItem>
                            <asp:ListItem Value="1">Present</asp:ListItem>
                            <asp:ListItem Value="3">unaccsebtable Absen</asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Mark">
                    <ItemTemplate>
                        <asp:Label ID="lbl_Text1" runat="server" Text='<%# Bind("Mark") %>'></asp:Label>
                        <asp:TextBox ID="txt_Text1" runat="server" Text='<%# Bind("Mark") %>' CssClass="hideControl"
                            AutoPostBack="true" OnTextChanged="Change"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Namespaces

C#

using System.Data;
using System.Configuration;
using System.Data.SqlClient;

VB.Net 

Imports System.Data.SqlClient
Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        BindGrid();
    }
}

private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM UpdateTable1", con))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                da.Fill(dt);
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
    }
}

protected void Change(object sender, EventArgs e)
{
    TextBox txtMark = sender as TextBox;
    string mark = txtMark.Text;
    GridViewRow row = (GridViewRow)txtMark.NamingContainer;
    string status = (row.FindControl("hfStatus") as HiddenField).Value;
    string query = "UPDATE UpdateTable1 SET AttendanceStatus = @Status,Mark = @Mark WHERE Id = @Id";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            cmd.Parameters.AddWithValue("@Status", status);
            cmd.Parameters.AddWithValue("@Mark", mark);
            cmd.Parameters.AddWithValue("@Id", row.Cells[0].Text);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    BindGrid();
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string status = (e.Row.FindControl("hfStatus") as HiddenField).Value;
        if (status == "1")
        {
            (e.Row.FindControl("lblStatus") as Label).Text = "Present";
        }
        else if (status == "2")
        {
            (e.Row.FindControl("lblStatus") as Label).Text = "acceptable Absent";
        }
        else if (status == "3")
        {
            (e.Row.FindControl("lblStatus") as Label).Text = "unaccsebtable Absent";
         }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        BindGrid()
    End If
End Sub

Private Sub BindGrid()
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand("SELECT * FROM UpdateTable1", con)
            Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
                Dim dt As DataTable = New DataTable()
                da.Fill(dt)
                GridView1.DataSource = dt
                GridView1.DataBind()
            End Using
        End Using
    End Using
End Sub

Protected Sub Change(ByVal sender As Object, ByVal e As EventArgs)
    Dim txtMark As TextBox = TryCast(sender, TextBox)
    Dim mark As String = txtMark.Text
    Dim row As GridViewRow = CType(txtMark.NamingContainer, GridViewRow)
    Dim status As String = (TryCast(row.FindControl("hfStatus"), HiddenField)).Value
    Dim query As String = "UPDATE UpdateTable1 SET AttendanceStatus = @Status,Mark = @Mark WHERE Id = @Id"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString

    Using con As SqlConnection = New SqlConnection(constr)

        Using cmd As SqlCommand = New SqlCommand(query, con)
            cmd.Parameters.AddWithValue("@Status", status)
            cmd.Parameters.AddWithValue("@Mark", mark)
            cmd.Parameters.AddWithValue("@Id", row.Cells(0).Text)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Using

    BindGrid()
End Sub

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim status As String = (TryCast(e.Row.FindControl("hfStatus"), HiddenField)).Value

        If status = "1" Then
            TryCast(e.Row.FindControl("lblStatus"), Label).Text = "Present"
        ElseIf status = "2" Then
            TryCast(e.Row.FindControl("lblStatus"), Label).Text = "acceptable Absent"
       If status = "3" Then
            TryCast(e.Row.FindControl("lblStatus"), Label).Text = "unaccsebtable Absent"
        End If
    End If
End Sub

Screenshot