简体   繁体   English

如何使用带有C#的ASP.NET在Gridview中实现批量保存

[英]How to achieve bulk save in Gridview using ASP.NET with C#

I have got a Gridview which gets populated with multiple rows as follows where user is allowed to edit Alternate names for the viewed rows after he can bulk save the edited columns. 我有一个Gridview,其中填充了多行,如下所示:在用户可以批量保存编辑后的列之后,允许用户编辑查看行的备用名称。

在此处输入图片说明

I tried achieving this using Edit template but I could not achieve this because when the user tries to edit the next row immediately the previous "edited" column contents are erased back to original. 我尝试使用“编辑”模板来实现此目的,但是却无法实现,因为当用户尝试立即编辑下一行时,先前的“已编辑”列内容将被擦除回原始值。

How can I achieve this using gridview 如何使用gridview实现此目的

On edit action of the GridView, your change happens only on your browser (client side) until you save the change of current row. 在GridView的编辑操作中,更改仅在浏览器(客户端)上发生,直到您保存当前行的更改为止。 You need to save the row and refresh GridView to begin editing the next row. 您需要保存该行并刷新GridView才能开始编辑下一行。

The typical implementation is to place two button on Edit template - Cancel and Save button to commit the change of the edited row. 典型的实现方式是在“编辑”模板上放置两个按钮-“取消”和“保存”按钮以提交对已编辑行的更改。 When clicking on the save button, your postback event will be picked up on server side code (with event argument e that contain which row was on edit and row data that you updated). 当单击保存按钮时,您的回发事件将在服务器端代码上拾取(事件参数e包含正在编辑的行和已更新的行数据)。 You save the data to database and refresh the GridView. 您将数据保存到数据库并刷新GridView。 At that moment, you should be able to see the GridView with updated content. 那时,您应该能够看到带有更新内容的GridView。 You are ready to click on the Edit button of the next row. 您准备单击下一行的“编辑”按钮。

Use this and Edit According to you this is working for me perfectly. 使用它并根据您的要求进行编辑,这对我来说是完美的。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />
    <script type="text/javascript">
        $(function () {

            $("[id$=txtRecievedDate]").datepicker({
                showOn: 'button',
                buttonImageOnly: true,
                dateFormat: "yy-mm-dd",
                buttonImage: 'http://jqueryui.com/demos/datepicker/images/calendar.gif'

            });
        });
     </script>
    <style type = "text/css">
    input[type=text], select{background-color:#FFFFD2; border:1px solid #ccc}
    </style>
</head>
<body style = "font-family:Arial;font-size:10pt">
    <form id="form1" runat="server">
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"  
        DataKeyNames = "id" onrowdatabound="gvCustomers_RowDataBound">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
            <asp:Label ID="Label1" runat="server" Text="SelectEdit"></asp:Label>
                <asp:CheckBox ID = "chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="ID" ItemStyle-Width = "150">
            <ItemTemplate>
                <asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
                <asp:TextBox ID="txtID" runat="server" Text='<%# Eval("id") %>' ReadOnly="true" Visible="false"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Cartridge Set No" ItemStyle-Width = "150">
            <ItemTemplate>
                <asp:Label ID="lblCartridgeSetNo" runat="server" Text='<%# Eval("CartridgeSetNo") %>'></asp:Label>
                <asp:TextBox ID="txtCartridgeSetNo" runat="server" Text='<%# Eval("CartridgeSetNo") %>' ReadOnly="true" Visible="false"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Status" ItemStyle-Width = "150">
            <ItemTemplate>
                <asp:Label ID = "lblcurrentstatus" runat="server" Text='<%# Eval("currentstatus") %>'></asp:Label>
                <asp:Label ID = "lblstatus" runat="server" Text='<%# Eval("status") %>' Visible = "false"></asp:Label>
                <asp:DropDownList ID="ddlstatus" runat="server" Visible = "false">

                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
                <asp:TemplateField HeaderText="date Recieved" ItemStyle-Width = "150">
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Eval("dateRecieved") %>'></asp:Label>
                <asp:TextBox ID="txtRecievedDate" runat="server" Text='<%# Eval("dateRecieved") %>' Visible="false"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Comments" ItemStyle-Width = "150">
            <ItemTemplate>
                <asp:Label ID="lblComments" runat="server" Text='<%# Eval("comments") %>'></asp:Label>
                <asp:TextBox ID="txtComments" runat="server" Text='<%# Eval("comments") %>'  Visible="false"></asp:TextBox>

            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick = "Update" Visible = "false"/>
    </form>
</body>
</html>

CS file CS文件

 using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Linq;
using System.Configuration;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.BindGrid();
        }
    }
    private void BindGrid()
    {
        SqlCommand cmd = new SqlCommand("SELECT   [Id],[CartridgeSetNo],[status] ,[dateRecieved],[Comments] ,case when status = 1 then 'Received but not usable' when status = 0 then 'Received and Usable' else 'Not Received' end as currentstatus FROM DrugAllocate ");
        gvCustomers.DataSource = this.ExecuteQuery(cmd, "SELECT");
        gvCustomers.DataBind();
    }
    private DataTable ExecuteQuery(SqlCommand cmd, string action)
    {
        string conString = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
        using (SqlConnection con = new SqlConnection(conString))
        {
            cmd.Connection = con;
            switch (action)
            {
                case "SELECT":
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            return dt;
                        }
                    }
                case "UPDATE":
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                    break;
            }
            return null;
        }
    }

    protected void Update(object sender, EventArgs e)
    {
        foreach (GridViewRow row in gvCustomers.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
                if (isChecked)
                {
                    SqlCommand cmd = new SqlCommand("UPDATE DrugReceipt SET Comments=@Comments,  dateRecieved=@dateRecieved , status = @status where Id = @Id");
                    cmd.Parameters.AddWithValue("@Comments", row.Cells[5].Controls.OfType<TextBox>().FirstOrDefault().Text);

                    string status = row.Cells[3].Controls.OfType<DropDownList>().FirstOrDefault().SelectedItem.Value;
                    if (status == "Received and Usable")
                    {
                        status="0";
                    }
                    if (status == "Received but not usable")
                    {
                       string comments=row.Cells[5].Controls.OfType<TextBox>().FirstOrDefault().Text;
                        status = "1";
                        if (comments == "")
                        {
                            ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('comment is mendatry');", true);
                            break;
                        }
                    }
                    if (status == "Not Received")
                    {
                        status = "2";
                    }
                    cmd.Parameters.AddWithValue("@status", status);
                    cmd.Parameters.AddWithValue("@dateRecieved", row.Cells[4].Controls.OfType<TextBox>().FirstOrDefault().Text);
                    cmd.Parameters.AddWithValue("@Id", gvCustomers.DataKeys[row.RowIndex].Value);
                    this.ExecuteQuery(cmd, "UPDATE");
                }
            }
        }
        btnUpdate.Visible = false;
        this.BindGrid();
    }
    public DataSet GetYesNoValue(string ColumnName)
    {
        DataTable dtVal = new DataTable();
        DataColumn column;


        column = new DataColumn();
        column.DataType = System.Type.GetType("System.String");
        column.ColumnName = ColumnName;
        dtVal.Columns.Add(column);

        DataSet dsVal = new DataSet();

        dtVal.Rows.Add("Received and Usable");
        dtVal.Rows.Add("Received but not usable");
        dtVal.Rows.Add("Not Received");

        dsVal.Tables.Add(dtVal);

        return dsVal;
    }
    protected void OnCheckedChanged(object sender, EventArgs e)
    {
        bool isUpdateVisible = false;
        CheckBox chk = (sender as CheckBox);
        if (chk.ID == "chkAll")
        {
            foreach (GridViewRow row in gvCustomers.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked = chk.Checked;
                }
            }
        }
        CheckBox chkAll = (gvCustomers.HeaderRow.FindControl("chkAll") as CheckBox);
        chkAll.Checked = true;
        foreach (GridViewRow row in gvCustomers.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {


                bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
                for (int i = 1; i < row.Cells.Count; i++)
                {


                    row.Cells[i].Controls.OfType<Label>().FirstOrDefault().Visible = !isChecked;
                    if (row.Cells[i].Controls.OfType<TextBox>().ToList().Count > 0)
                    {
                        row.Cells[i].Controls.OfType<TextBox>().FirstOrDefault().Visible = isChecked;
                    }
                    if (row.Cells[i].Controls.OfType<DropDownList>().ToList().Count > 0)
                    {
                        row.Cells[i].Controls.OfType<DropDownList>().FirstOrDefault().Visible = isChecked;
                    }
                    if (isChecked && !isUpdateVisible)
                    {
                        isUpdateVisible = true;
                    }
                    if (!isChecked )
                    {
                        chkAll.Checked = false;
                    }

                }
            }
        }
        btnUpdate.Visible = isUpdateVisible;
    }
    protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            SqlCommand cmd = new SqlCommand("SELECT status,  case when status = 1 then 'Received but not usable' when status = 0 then 'Received and Usable' else 'Not Received' end as statuscurrent FROM DrugAllocate");
            DropDownList ddlstatus = (e.Row.FindControl("ddlstatus") as DropDownList);
            ddlstatus.DataSource = this.ExecuteQuery(cmd, "SELECT");
            string country = (e.Row.FindControl("lblstatus") as Label).Text;
            DataSet ds = new DataSet();
            ds = GetYesNoValue("suppStatus");
            DataTable dt = new DataTable();
            dt = ds.Tables[0];
            ddlstatus.DataSource = dt;
            ddlstatus.DataTextField = "suppStatus";
            ddlstatus.DataValueField = "suppStatus";
            ddlstatus.DataBind();
            try
            {
                ddlstatus.Items.FindByValue(country).Selected = true;
            }
            catch { }

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM