使用gridview更新数据集值
本文关键字:数据集 更新 gridview 使用 | 更新日期: 2024-10-19 21:13:28
我有一个网格视图:
折扣.aspx
<asp:GridView ID="GridView2" runat="server" BackColor="White"
BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3"
CellSpacing="1" GridLines="None">
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
</asp:GridView>
我在Discount.aspx上的数据集中填写它。cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class Discount : System.Web.UI.Page
{
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
DBservices db2 = new DBservices();
SqlConnection con = db2.connect("storeConnectionString");
string SelectSTR = "SELECT * FROM Items";
SqlDataAdapter da = new SqlDataAdapter(SelectSTR, con);
da.Fill(ds);
GridView2.DataSource = ds;
GridView2.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
int price;
for (int i = 0; i < GridView2.Rows.Count; i++)
{
if (Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[4]) > Convert.ToInt32(minamount.Text))
{
price = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[2]);
price= price*((100- Convert.ToInt32(discountrate.Text))/100);
ds.Tables[0].Rows[i].ItemArray[4] = price;
GridView2.DataBind();
}
}
}
}
正如你所看到的,我试图更新数据集中的价格列,然后更新网格视图,但问题是网格视图没有任何变化。。。。
谢谢你,祝你今天愉快
您需要使用数据源重新绑定网格
GridView2.DataSource = ds; //missing
GridView2.DataBind();
您错过了按钮点击事件中的第一行:
声明全局数据适配器;
则更改值后:
da.update() // Saves Changes to database
更新2:
SqlDataAdapter da = new SqlDataAdapter(SelectSTR, con);
make changes to dataset
da.update() // save changes to database
NOte:在外部声明数据适配器,以便在两个方法中都可以访问它
单击按钮时没有指定网格视图的数据源。请注意,这些更改不会更新到数据库(您的呼叫)。
protected void Button1_Click(object sender, EventArgs e)
{
int price;
for (int i = 0; i < GridView2.Rows.Count; i++)
{
if (Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[4]) > Convert.ToInt32(minamount.Text))
{
price = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[2]);
price= price*((100- Convert.ToInt32(discountrate.Text))/100);
ds.Tables[0].Rows[i].ItemArray[4] = price;
Gridview2.DataSource=ds;
GridView2.DataBind();
}
}
}