如何从Gridview获取行并将其插入数据库?

时间:2014-07-07 10:11:21

标签: c# asp.net sql gridview

我正在为制药实验室开发一个Web应用程序。

在从客户处获取订单并单击提交按钮时,我已将数据插入到我的数据库的三个表中(customer,orderMaster,orderDetail)。我已插入customer和orderMaster表。对于orderDetail,我必须从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();
    }
}

我使用了断点而没有获得Serial No列的任何值。因为我在Serial No列的自动增量上使用了模板字段。 这是我的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>

2 个答案:

答案 0 :(得分:1)

这会将您的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;
        }

以上是通用功能,您可能需要调整它以适合您的具体情况。

如果遍历数据表,则可以将其重新插入数据库。您似乎能够根据现有代码写入数据库,如果需要帮助,请在评论中发帖。

答案 1 :(得分:0)

感谢我的所有问题都已解决..我已将网格视图模板字段更改为绑定字段并在编码中完成增量。

int j = 1;
        foreach (GridViewRow item in GridView1.Rows)
        {
            item.Cells[1].Text = j++.ToString();

        }