Edit ASP.Net GridView cell on Click with DropdownList value using jQuery in C# and VB.Net

Last Reply 3 months ago By dharmendr

Posted 3 months ago

I have a DropdownList in my gridview. now I don't want to click on the edit button for update my data. I just want click on the field and then the dropdown list shows to me. after that I select the value update my data. 

            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id">
                <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:DropDownList ID="DropDownList1" runat="server">
                                <asp:ListItem Value="0">Absent</asp:ListItem>
                                <asp:ListItem Value="1">Present</asp:ListItem>
                            </asp:DropDownList>
                        </ItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("AttendanceStatus") %>'></asp:Label>
                        </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>

 

    <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('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('input[type=text]').val(val);
                    $(this).find('input[type=text]').show();
                    $(this).find('input[type=text]').focus();
                }
            });
        });
    </script>

 

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

        private void BindGrid()
        {
            string constr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM EDU_Lesson2", 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;
            GridViewRow row = (GridViewRow)txtMark.NamingContainer;
            string query = "UPDATE EDU_Lesson2 SET Mark = @Mark WHERE Id = @Id";
            string constr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    cmd.Parameters.AddWithValue("@Mark", txtMark.Text);
                    cmd.Parameters.AddWithValue("@Id", row.Cells[0].Text);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
            BindGrid();
        }

how can I do this?

Posted 3 months ago

Hi dorsa,

Check this example. Now please take its reference and correct your code.

HTML

C#

<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 != "") {
                    $(this).closest('tr').find('[id*=lblStatus]').html(status >= 1 ? "Present" : "Absent");
                    $(this).closest('tr').find('[id*=hfStatus]').val(status);
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id">
        <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").ToString() == "False" ? "Absent" : "Present" %>'></asp:Label>
                    <asp:DropDownList ID="DropDownList1" runat="server" CssClass="hideControl">
                        <asp:ListItem Value="">Select</asp:ListItem>
                        <asp:ListItem Value="0">Absent</asp:ListItem>
                        <asp:ListItem Value="1">Present</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>
    </form>
</body>
</html>

VB.Net

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" 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 != "") {
                    $(this).closest('tr').find('[id*=lblStatus]').html(status >= 1 ? "Present" : "Absent");
                    $(this).closest('tr').find('[id*=hfStatus]').val(status);
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id">
        <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='<%# If(Eval("AttendanceStatus").ToString() = "False", "Absent", "Present") %>'></asp:Label>
                    <asp:DropDownList ID="DropDownList1" runat="server" CssClass="hideControl">
                        <asp:ListItem Value="">Select</asp:ListItem>
                        <asp:ListItem Value="0">Absent</asp:ListItem>
                        <asp:ListItem Value="1">Present</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>
    </form>
</body>
</html>

Namespaces

C#

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

VB.Net

Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient

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 UpdateTable", 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;
    GridViewRow row = (GridViewRow)txtMark.NamingContainer;
    string status = (row.FindControl("hfStatus") as HiddenField).Value.Trim();
    string query = "UPDATE UpdateTable SET Mark = @Mark, AttendanceStatus = @Status 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("@Mark", txtMark.Text);
            cmd.Parameters.AddWithValue("@Status", status);
            cmd.Parameters.AddWithValue("@Id", row.Cells[0].Text);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    BindGrid();
}

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 UpdateTable", 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 row As GridViewRow = CType(txtMark.NamingContainer, GridViewRow)
    Dim status As String = (TryCast(row.FindControl("hfStatus"), HiddenField)).Value.Trim()
    Dim query As String = "UPDATE UpdateTable SET Mark = @Mark, AttendanceStatus = @Status 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("@Mark", txtMark.Text)
            cmd.Parameters.AddWithValue("@Status", status)
            cmd.Parameters.AddWithValue("@Id", row.Cells(0).Text)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Using
End Sub

Screenshot


Posted 3 months ago

Thx dharmendr ,

If I want to change the place of fields Like below, I should change which part of the code?!

 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id">
        <Columns>
             <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").ToString() == "False" ? "Absent" : "Present" %>'></asp:Label>
                    <asp:DropDownList ID="DropDownList1" runat="server" CssClass="hideControl">
                        <asp:ListItem Value="">Select</asp:ListItem>
                        <asp:ListItem Value="0">Absent</asp:ListItem>
                        <asp:ListItem Value="1">Present</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>
            <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" />  
        </Columns>
    </asp:GridView>

 


Posted 3 months ago

Use this code.

<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 ? "Present" : "Absent");
                $(this).closest('tr').find('[id*=hfStatus]').val(status);
            }
        });
    });
</script>

In code behind change the cell position to get the Id according to the column index.

cmd.Parameters.AddWithValue("@Id", row.Cells[0].Text);