使用C#ASP的带有子GridView的主GridView的网站.NET



所以我有一个网站,它使用带有子GridView的主GridView。

我想复制(克隆(现有行,并将其粘贴回主GridView。

使用下面的代码,我得到了这个错误,因为填充子GridView的MySql中的SProc找不到预期的参数

Exception Details:
MySql.Data.MySqlClient.MySqlException: 
Incorrect integer value: '' for column 'tcustomerId' at row 1

在主GridView上我设置了

DataKeyNames="CustomerId"

关于子GridView(进入gvProducts_RowDataBound(

string CustomerId = gvProducts.DataKeys[e.Row.RowIndex].Value.ToString();

在VS 2019上,调试cmdCopy_Click事件中的值返回,这是正确的

CustomerId = Convert.ToInt32(index).ToString(); 

线路错误为1027

Line 1025:                            MySqlDataAdapter adapter = new MySqlDataAdapter();
Line 1026:                            adapter = new MySqlDataAdapter(cmd);
Line 1027:                            adapter.Fill(ds);
Line 1028:                            cmd.Connection.Close();

谢谢你的建议。

protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.DataItem != null)
{
GridView gv_Child = (GridView)e.Row.FindControl("gv_Child");

if (gv_Child != null)
{
string CustomerId = gvProducts.DataKeys[e.Row.RowIndex].Value.ToString();
DataSet ds = new DataSet();

using (MySqlConnection cn =
new MySqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (MySqlCommand cmd =
new MySqlCommand("SProc", cn))
{
cmd.Connection.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("tcustomerId", customerId);

MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter = new MySqlDataAdapter(cmd);
adapter.Fill(ds);
cmd.Connection.Close();

gv_Child.DataSource = ds.Tables[0];
gv_Child.DataBind();
}
}
}
}
}
}

protected void cmdCopy_Click(object sender, ImageClickEventArgs e)
{
GridViewRow gvRow = (sender as ImageButton).NamingContainer as GridViewRow;
int index = gvRow.RowIndex;
CustomerId = Convert.ToInt32(index).ToString();

HiddenField hd = gvRow.FindControl("hf") as HiddenField;
string hValue = hd.Value.ToString().Replace('.',',');

DataTable dt = RetrieveProducts();
DataRow dr = dt.NewRow();
dr["tValue"] = hValue;
dt.Rows.InsertAt(dr, index + 1);

BindData();
}

获取gv索引,然后从索引中获取该行的datakey(隐藏的PK值(。数据键的整体思想是,您可以获得PK行值,但不必将其包含在标记中。

因此,为此";"复制";,获取索引,然后使用DataKeys数组中的索引来获取customerID(datakey(。

行idex很简单——行数从0开始,然后是1,然后是2——因此rowindex可以得到行号,而不是PK或datakey值。

例如:

GridViewRow gvRow = (sender as ImageButton).NamingContainer as GridViewRow;
int index = gvRow.RowIndex;
int CustomerId = (int)MyGrid.DataKeys[index]["CustomerID"];

现在,您可以将CustomerID替换为您的数据键设置,但您没有共享asp:GridView行的GV标记,所以我们看不到。

然而,我看不出行数据绑定是如何使用的,因为它在每次和每一行都会触发——因此设置全局字符串customerId在这里没有意义。因此,声明CustomerID,并使用行索引来获取数据键设置。

如前所述,我必须猜测datakeys设置,但使用任何名称,通过使用行索引,您可以获得PK行值。

并且行数据绑定仅在绑定期间触发。因此,您所拥有的单独的行单击事件将永远不会看到或获得页面范围的宽字符串CustomerID,因为它将只具有/保持LAST行数据绑定事件,我看不到该事件是任何值,也看不到它在行单击复制事件中使用。这两件事彼此关系不大。

最新更新