c# - 如何从 Gridview 中获取行并将它们插入数据库?

标签 c# asp.net sql gridview

我正在为制药实验室开发网络应用程序。

在从客户处获取订单并单击提交按钮时,我已将数据插入到我的数据库的三个表中(客户、orderMaster、orderDetail)。我已插入客户和 orderMaster 表。对于 orderDetail,我必须从 gridview 中插入数据。

当我添加针对客户的测试时,该测试会添加到 GridView 中。一个 GridView 可以针对一个客户进行多项测试。

如何从 GridView 向数据库插入数据?

我从 gridview 获取数据并将其插入数据库的函数是:

private void bindOrderDetails()
{
    database_connectivity dbConnect = new database_connectivity();
    SqlConnection con = new SqlConnection();
    con = dbConnect.ConnectDB();
    con.Open();
    SqlCommand cmmd = new SqlCommand("SELECT MAX(orderID) as Order_Id FROM testOrder_master WHERE user_id = '" + Convert.ToInt32(txtUserID.Text) + "'", con);
    cmmd.Connection = con;
    SqlDataReader dr1 = cmmd.ExecuteReader();
    int orderID = 0;
    while (dr1.Read())
    {
        orderID = Convert.ToInt32(dr1["Order_Id"]);
    }
    con.Close();
    //for (int i = 0; i < GridView1.Rows.Count - 1; i++)
    //{
    //    Stquery = @"INSERT INTO testOrder_details (orderID, labID, srNo, test_id, price, createdBy, creationTime) VALUES ('"+orderID+"','"+Convert.ToInt32(txtLabID.Text)+"','"+Convert.ToString(GridView1.Rows[i].Cells[1].
    //}

    foreach (GridViewRow row in GridView1.Rows)
    {
        con.Open();
        SqlCommand cmd1 = new SqlCommand("INSERT INTO testOrder_details (orderID, labID, srNo, test_id, price, createdBy, creationTime) VALUES (@orderId1,@lab_id,@serialNo,@testID, @testPrice, @created_by, @creation_time)", con);
        cmd1.Parameters.AddWithValue("@orderId1", orderID);
        cmd1.Parameters.AddWithValue("@lab_id", Convert.ToInt32(txtLabID.Text));
        cmd1.Parameters.AddWithValue("@serialNo", row.Cells[1].Text);
        cmd1.Parameters.AddWithValue("@testID", row.Cells[2].Text);
        cmd1.Parameters.AddWithValue("@testPrice", row.Cells[4].Text);
        cmd1.Parameters.AddWithValue("@created_by", Convert.ToString(txtUserTitle.Text));
        cmd1.Parameters.AddWithValue("@creation_time", DateTime.Now);
        cmd1.ExecuteNonQuery();
    }
}

我使用了断点,但未获得序列号列的任何值。因为我在序列号列的自动递增上使用了模板字段。 这是我的 gridview 的 asp 代码:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    BackColor="White" BorderColor="#CCCCCC" 
    BorderStyle="None" BorderWidth="1px" CellPadding="3"
    onrowdeleting="GridView1_RowDeleting" 
    onselectedindexchanged="GridView1_SelectedIndexChanged"
    onrowcommand="GridView1_RowCommand" 
    onrowdatabound="GridView1_RowDataBound">
    <Columns>
        <asp:CommandField ShowDeleteButton="True" ButtonType="Image" 
            DeleteImageUrl="~/Imagess/delete.jpg" />
        <asp:TemplateField HeaderText="Serial No">
            <ItemTemplate><%# Container.DataItemIndex + 1 %>
            </ItemTemplate>
            <ItemStyle Width="2%" /> 
        </asp:TemplateField>

        <asp:BoundField DataField="testID" HeaderText="Test ID" />
        <asp:BoundField DataField="testName" HeaderText="Test Name" />
        <asp:BoundField DataField="testPrice" HeaderText="Price" />
    </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>

最佳答案

这会将您的 gridview 转换为数据表:

DataTable GetDataTable(GridView dtg)
        {
            DataTable dt = new DataTable();

            // add the columns to the datatable            
            if (dtg.HeaderRow != null)
            {

                for (int i = 0; i < dtg.HeaderRow.Cells.Count; i++)
                {
                    dt.Columns.Add(dtg.HeaderRow.Cells[i].Text);
                }
            }

            //  add each of the data rows to the table
            foreach (GridViewRow row in dtg.Rows)
            {
                DataRow dr;
                dr = dt.NewRow();

                for (int i = 0; i < row.Cells.Count; i++)
                {
                    dr[i] = row.Cells[i].Text.Replace(" ", "");
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

以上是通用函数,您可能需要对其进行调整以适应您的特定情况。

如果您遍历数据表,您可以将其插入回数据库中。您似乎能够根据现有代码写入数据库,如果您需要这方面的帮助,请发表评论。

关于c# - 如何从 Gridview 中获取行并将它们插入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24608128/

相关文章:

ASP.NET网站发布成功后显示503 Service Unavailable

mysql - mysql查询的左连接还是联合?

asp.net - 如何在IIS6.0服务器的asp.net2.0中更改服务器响应头

mysql - Sequelize Eager Loading 两个相同的 N :M models one returns data other does not

SQL GetDate() 返回错误的时间

c# - Xunit 测试自定义消息的 IHttpActionResult Web api 2 函数

c# - 从代码中获取 dll 引用的项目名称

c# - 当作为 Windows 服务运行时,如何让程序自己截屏?

c# - 无法在Windows 10机器上构建IdentityServer4

javascript - Visual Studio 显示错误