直接编辑GridView中的文本并保存到数据库

In order to make each cell editable, we can use the TextBox control to fill the GridView‘s cell. We can use “TemplateField.ItemTemplate” property to set the template for displaying an item in a data-bound control.

Relevant .aspx file please refer to the following code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="directly_input_GridView.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
                <Columns>
                    <asp:TemplateField HeaderText="ID">
                        <ItemTemplate>
                            <asp:Label ID="txt_id" runat="server" Text='<%# Eval("Id") %>' BorderStyle="None"></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Name">
                        <ItemTemplate>
                            <asp:TextBox ID="txt_name" runat="server" Text='<%# Eval("Name") %>' BorderStyle="None" OnTextChanged="Value_TextChanged" AutoPostBack="True"></asp:TextBox>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Age">
                        <ItemTemplate>
                            <asp:TextBox ID="txt_age" runat="server" Text='<%# Eval("Age") %>' BorderStyle="None" OnTextChanged="Value_TextChanged" AutoPostBack="True"></asp:TextBox>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

In .aspx, we subscribe to the event " OnTextChanged " to detect whether the text has changed.

The specific "Value_TextChanged" method is as follows.

    protected void Value_TextChanged(object sender, EventArgs e)
    {
        TextBox txt = (TextBox)sender;
        GridViewRow gvr = (GridViewRow)txt.Parent.Parent;
        string id = ((Label)gvr.FindControl("txt_id")).Text;
        using (SqlConnection conn = new SqlConnection(constr))
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            if (((TextBox)sender).ID == "txt_name")
            {
                cmd.CommandText = $"update name_age set Name=@Name where Id='{id}'";
                cmd.Parameters.AddWithValue("@Name", ((TextBox)sender).Text);
            }
            else if (((TextBox)sender).ID == "txt_age")
            {
                cmd.CommandText = $"update name_age set Age=@Age where Id='{id}'";
                cmd.Parameters.AddWithValue("@Age", ((TextBox)sender).Text);
            }
            cmd.ExecuteNonQuery();
        }
    }

Or more dynamicly,

    protected void Value_TextChanged(object sender, EventArgs e)
    {
        TextBox txt = (TextBox)sender;
        // get the name of co
        GridViewRow row = (GridViewRow)txt.NamingContainer;
        string columnName = txt.UniqueID.Split('_')[1].ToString();

        GridViewRow gvr = (GridViewRow)txt.Parent.Parent;
        string id = ((Label)gvr.FindControl("txt_id")).Text;
        using (SqlConnection conn = new SqlConnection(constr))
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;

            cmd.CommandText = $"update name_age set {columnName}=@text where Id='{id}'";
            cmd.Parameters.AddWithValue("@text", ((TextBox)sender).Text);

            cmd.ExecuteNonQuery();
        }
    }

And here is the code to read data from the database.

    string constr = @"Data Source=(localdb)MSSQLLocalDB;Initial Catalog=Test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            using (SqlConnection conn = new SqlConnection(constr))
            {
                SqlDataAdapter sda = new SqlDataAdapter("Select * From name_age", conn);
                DataSet Ds = new DataSet();
                sda.Fill(Ds, "T1");
                GridView1.DataSource = Ds.Tables[0];
                GridView1.DataBind();
            }
        }
    }

The T-SQL statement of the Table used for testing is shown below.

CREATE TABLE [dbo].[name_age] (
    [Id]   INT        NOT NULL,
    [Name] NCHAR (10) NULL,
    [Age]  NCHAR (10) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

The demo gif.

原文地址:https://www.cnblogs.com/jizhiqiliao/p/12973605.html