如何使按钮可访问字符串?

时间:2019-02-14 12:50:47

标签: c# asp.net

我需要保存从选择要在受按钮保护的void中使用的行时得到的刺痛。

protected void Button2_Click(object sender, EventArgs e)
{
    string = id <= how to get the string here?
}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow row = GridView1.SelectedRow;
    string id = row.Cells[3].Text;
}

4 个答案:

答案 0 :(得分:0)

您可以将获取ID的代码移至某个属性,例如:

protected void Button2_Click(object sender, EventArgs e)
{
    string id = SelectedId;
}

private string SelectedId 
{
  get
  {
    GridViewRow row = GridView1.SelectedRow;
    return row?.Cells[3].Text; // Please note the check against null (row?)
  }
}

答案 1 :(得分:0)

最简单的是:

将Button2设置为在启动时禁用......

protected void Button2_Click(object sender, EventArgs e)
{
    string id = GridView1.SelectedRow.Cells[3].Text;
}

// only allow the button to be enabled if there is a selected row
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{        
    if (GridView1.SelectedRow != null){
        Button2.Enabled = true;
    } else {
        Button2.Enabled = false;
    }
}

答案 2 :(得分:-1)

使用会话代替在函数内部初始化String,它将存储您的值,您可以在代码中的任何位置访问它。

protected void Button2_Click(object sender, EventArgs e)
{
    lblanything.Text = Session["id"].ToString();
}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow row = GridView1.SelectedRow;
    Session["id"] = row.Cells[3].Text;
}

希望它会解决您的问题。

答案 3 :(得分:-1)

您可以将字符串定义为“静态”,然后尝试访问该值。

//Defining id as Static

public partial class MyPage: System.Web.UI.Page
{

       static string id = String.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {

        }
 }

//Setting the Static variable to a value

protected void MyGridView_SelectedIndexChanged(object sender, EventArgs e)
{

    GridViewRow row = MyGridView.SelectedRow;

    id = row.Cells[3].Text;

}

//Assigning the Static variable

protected void MyButton_Click(object sender, EventArgs e)
{

    lable1.Text = id;

}