Gridview单元格在Asp.NET

时间:2016-02-07 10:51:29

标签: c# asp.net gridview

我正在Asp.net(Framework 4.0)中创建网站。

在这个网站上,我采用了一个Gridview,其中填充了页面加载的数据。

现在我正在尝试在按钮点击时将数据从Gridview插入数据库。插入数据库时​​,GridView Cells显示空白值。

GridView绑定的代码如下

void BindGrid()
 {
   GridView1.DataSource = obj3.GetCart(sid, uid);
   GridView1.DataBind();
   int rowCount = GridView1.Rows.Count;
   if (rowCount == 0)
    {
       GridView1.Visible = false;
       lblCartCount.Visible = true;
       lblCartCount.Text = " No Items In Cart";
    }
    else
    {
       GridView1.Visible = true;
       GridView1.FooterRow.Cells[3].Text = "Total Price";
       GridView1.FooterRow.Cells[3].HorizontalAlign = HorizontalAlign.Right;
       GridView1.FooterRow.Cells[9].Text = totals.ToString();
       totprice = Convert.ToInt32(totals.ToString());
       totals = 0;
       lblCartCount.Visible = false;
   }
 }

“插入代码”按钮单击“将数据从Gridview插入数据库”。

 protected void btnOrderNow_Click(object sender, EventArgs e)
{
    foreach (GridViewRow g1 in GridView1.Rows)
    {
        BindGrid();
        val1 = obj4.AddOrderItem(orderid, Convert.ToInt32(g1.Cells[2].Text),
        Convert.ToInt32(g1.Cells[5].Text), Convert.ToInt32(g1.Cells[4].Text),
        Convert.ToInt32(g1.Cells[6].Text), Convert.ToInt32(g1.Cells[7].Text),
        g1.Cells[0].Text, Convert.ToInt32(g1.Cells[1].Text));
    }
}

1 个答案:

答案 0 :(得分:0)

我自己找到了答案。将数据从Gridview插入数据库的代码有一些以下更改。

protected void btnOrderNow_Click(object sender, EventArgs e)
{
    foreach (GridViewRow g1 in GridView1.Rows)
    {
        string sss = (((Label)(g1.Cells[g1.RowIndex].FindControl("lblSession"))).Text.Trim());
        int uuu = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("Label5"))).Text.Trim());
        int itemid = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblItemId"))).Text.Trim());
        int priceid = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblPriceId"))).Text.Trim());
        int quantity = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblItemQuantity"))).Text.Trim());
        int price = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblPrice"))).Text.Trim());
        int bprice = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblBulkPrice"))).Text.Trim());

        val2 = obj4.OrderTempCartUpdate(sss, uuu);
    }

}

在此而不仅仅采用g1.Cells [0] .text无法找到特定的行索引。所以我补充说 (((标签)(g1.cells [g1.RowIndex] .FindControl( “标签”)))。

而不是g1.Cells [0] .text;