zoukankan      html  css  js  c++  java
  • 直接编辑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.

  • 相关阅读:
    pyppeteer
    maven生命周期clean,compile,install,package区别
    centos7安装anyproxy
    安装jupyter notebook
    Linux-Centos7下安装Anaconda
    python文件 启动django项目
    PyCharm实用插件
    pyqt5 安装额外的工具
    PyQt5高级界面控件之QTableWidget的具体使用方法
    k8s Metrics Server 获取资源指标与 hpa 部署
  • 原文地址:https://www.cnblogs.com/jizhiqiliao/p/12973605.html
Copyright © 2011-2022 走看看