【发布时间】:2012-01-16 16:40:57
【问题描述】:
在我的 ASP.NET 页面中,我使用 GridView 来查看数据(商品及其价格)。目前用户可以逐行编辑网格中的数据(价格)。 (单击-->“编辑”链接,更改值然后“更新”)。这是逐行的。是否可以在编辑模式下打开所有行并使用单个按钮(例如提交)一次更新所有数据?
【问题讨论】:
在我的 ASP.NET 页面中,我使用 GridView 来查看数据(商品及其价格)。目前用户可以逐行编辑网格中的数据(价格)。 (单击-->“编辑”链接,更改值然后“更新”)。这是逐行的。是否可以在编辑模式下打开所有行并使用单个按钮(例如提交)一次更新所有数据?
【问题讨论】:
如果您不需要只读模式,在这种情况下,您可以将输入框(文本框、下拉列表等)放在ItemTEmplate 部分并将它们与现有数据绑定。
接下来,在 GridView 的上方/下方放置一个提交按钮并处理按钮Click 事件并循环遍历GridView 项目数据并保存所有数据库。
如果您需要,我会发布代码块。感谢您的宝贵时间。
【讨论】:
使用 listview 而不是 gridview,您将可以更好地控制您所做的事情。
我的最佳做法是使用列表视图和自定义 Web 用户控件来解决此类问题。
如果你用你的用户控件填充你的列表视图,你将很容易管理你的保存方法,只需要迭代列表视图项目,找到控制并为每个项目调用你的 Save() 方法。
【讨论】:
我知道这个问题已经得到解答,但这里是循环通过 GridView 获取数据并将其存储在数据库中的代码:
使用库:
代码背后:
// this is a variable that have the Query or SQL Commands.
string DataBaseQuery = "UPDATE [table] SET [variable2] = @variable2, [variable3] = @variable3) WHERE [variable1] = @variable1";
//Click Event from a LinkButton.
protected void LinkButton1_Click(object sender, EventArgs e)
{
//"ConnectionString" its the string connection for your DataBase (often get from the WebConfig File or a DataSource element.
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
//this is for open the database using the string connection.
connection.Open();
//this is the algorithm for going through the entire GridView.
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//"DataBaseQuery" it's a string variable that have the Query or SQL Commands.
SqlCommand cmd = new SqlCommand(DataBaseQuery, conexion);
//this case it's for obtain the text variable of the first column of the gridview (in my case it was the ID of the register).
cmd.Parameters.AddWithValue("@variable1", ((Label)GridView1.Rows[i].Cells[0].FindControl("Label1")).Text.ToString());
//this case it's for obtain the selected value of a DropDownList that were in the 14 th column)
cmd.Parameters.AddWithValue("@variable2", ((DropDownList)GridView1.Rows[i].Cells[15].FindControl("DropDownlist2")).SelectedValue.ToString());
//this command it's for obtain the text of a textbox that is in the 15 th column of the gridview.
cmd.Parameters.AddWithValue("@variable3", ((TextBox)GridView1.Rows[i].Cells[16].FindControl("TextBox17")).Text.ToString());
cmd.ExecuteNonQuery();
}
//after going through all the gridview you have to close the connection to the DataBase.
connection.Close();
}
}
当然,您必须根据您的具体情况调整代码,但这很容易。在此代码中,您可以通过示例获取网格视图中其他对象(如 labes、文本框和下拉列表)的值。
为了运行这段代码我付出了很多(我不是很好的编程),但我很乐意提供帮助。
注意:要计算 gridview 的列,您必须从零开始。 注2:顺便说一句,对不起我的英语不好……这不是我的自然语言。
【讨论】: