簡體   English   中英

使用ASP.NET中的超鏈接編輯gridview中的行

[英]Edit row in gridview with hyperlink in ASP.NET

我有一個顯示產品實例信息的gridview; 我需要在“操作”列中添加一個超鏈接,以顯示一個顯示行數據的視圖/編輯頁面。 如何使鏈接將特定行中的數據顯示到編輯頁面?

注意:還有其他類似標題的問題,但是,它們不包含此特定主題。

嘗試這樣的事情?

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"]);
                ...
            }
            ...
        }
     }

在gridview中使用datakeys,使用datakey將獲取每個單擊的超鏈接的ID,然后您可以使用該ID輕松編輯或刪除所選項目。 在后面的代碼中找到超鏈接控件,傳遞數據鍵並為其寫入d update 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,它會減少您的代碼。

有n + 1種方法可以解決這個問題。 如果您正在使用sql數據源,那么如果您沒有特定要求,您可以為VS生成sql和編輯邏輯。 這是一個代碼項目教程

另一個常用的策略是向行添加一個命令按鈕,並使用要編輯的行的ID填充命令參數,然后在oncommand事件句柄中填充您需要的邏輯。

你也可以使用一個簡單的html鏈接,並使用get參數。 或者你可以像我說的那樣會話有很多方法可以解決這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM