我有一个gridview显示产品实例信息;我需要一个超链接在我的行动列,以提出一个视图/编辑页面,显示行数据。如何使链接将该特定行的数据调出到编辑页面中?
注意:还有其他类似题目的问题,但是,它们不包括这个特定的主题。
在gridview中使用datakey,使用datakey将获得每个单击的超链接的id,然后您可以使用该id轻松编辑或删除所选项目。在后面的代码中,只需找到超链接控件,传递数据键并为其编写更新sql。为了将您的数据移动到其他页面,您可以使用会话,但如果您正在开发一个商业网站,由于其安全问题,会话不是一个好主意,在这种情况下使用cookie。
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["productID"] != null)
{
productID = Convert.ToInt32(Request.QueryString["productID"]);
bindData(productID)
}
...
}
}
protected void bindData(int productID)
{
//to avoid sql injection as mentioned below use parameters
SqlConnection conn = new SqlConnection(ConnectionString); // define connection string globally or in your business logic
conn.Open();
SqlCommand sql = new SqlCommand("Select * From [Table] Where ID = @productID",conn);
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@ID";
parameter.Value = productID;
sql.Parameters.Add(parameter);
conn.close()
}
你也可以使用Microsoft.ApplicationBlocks.Data.dll来避免重复ado.net,它会减少你的代码。
试试这样做?
ViewProducts.aspx:
<columns>
<asp:HyperLinkField DataNavigateUrlFields="ProductID" HeaderText="Edit"
ItemStyle-Width="80"
DataNavigateUrlFormatString="EditProduct.aspx?productID={0}"
Text="Select" ItemStyle-HorizontalAlign="Center" />
...
</columns>
EditProduct.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["productID"] != null)
{
productID = Convert.ToInt32(Request.QueryString["productID"]);
...
}
...
}
}
有n+1种方法可以解决这个问题。如果你使用sql数据源,你可以让VS生成sql和编辑逻辑,如果你没有特定的要求。这是一个代码项目教程。
另一个常用的策略是向行添加一个命令按钮,并使用您想要编辑的行ID填充命令参数,然后在oncommand事件处理您需要的任何逻辑。
也可以使用简单的HTML链接和get参数。或者你可以像我说的,有很多方法可以解决这个问题。