2

まず第一に、私は新しい C# 開発者であり、助けが必要です。aspx ファイルに、ID/名前/ジョブの 3 つの列といくつかのレコード (行) を含む SqlDataSource を含むグリッド ビューがあります。ユーザーが行を選択すると、別のページにリダイレクトし、行の選択された ID の値をパラメーターとして渡したいと思います。ユーザーは、毎回 1 つの行のみを選択できます。私はそれに数時間を費やしましたが、奇妙なことが起こりました。

方法があります

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       string selectedID;

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            GridViewRow gvr = e.Row;
            selectedID = (GridView1.DataKeys[e.Row.RowIndex].Value.ToString());
            gvr.Attributes.Add("OnClick","javascript:location.href='Views/EditMenus/EditCompany.aspx?id=" + selectedID + "'");

            gvr.Attributes.Add("onmouseover", "this.style.backgroundColor='#FFE6E6'");
            gvr.Attributes.Add("onmouseout", "this.style.backgroundColor=''");
            gvr.Attributes.Add("style", "cursor:pointer;");

            Session["IDs"] = selectedID;
     } }

私のリダイレクトページでは、ページロードメソッドに次のコードがあります:

 protected void Page_Load(object sender, EventArgs e)
    {
          if (Session["IDs"] != null)
        {            
            Label2.Text = "Selected ID is: "+ Session["IDs"].ToString();
         }
    }

行を選択すると、他のページへのリダイレクトが正しく機能し、ブラウザの URL には上記の JavaScript コードに従って選択された ID の正しい値が含まれますが、Label2.Text は間違った ID を出力します。選択した ID の値の代わりに、各ページの最後の行の値 ID を出力します。なぜそれが起こるのですか?

上記のように、両方のケースで同じ変数「selectedID」を使用しているため、私にとっては少し奇妙です。

4

1 に答える 1

1

あなたはあなたのイベントであなたのID変数Sessionの値を痛める必要がありますSelectedIndexChangedGridView

void CustomersGridView_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
  {

    // Get the currently selected row.
    //Because the SelectedIndexChanging event occurs  before the select operation
    //in the GridView control, the SelectedRow property cannot be used.
    //Instead, use the Rows collection
    //and the NewSelectedIndex property of the 
    //e argument passed to this event handler.

    GridViewRow row = CustomersGridView.Rows[e.NewSelectedIndex];

    //Cells[0] is for first column so assign according to your column for ID
    Session["IDs"]=row.Cells[0].Text;


  }
于 2012-11-09T08:54:18.060 に答える