C#新手求助:如何将变量值传递至其他方法?
解决C# Web Forms中变量跨方法传递的问题
嘿,我能明白你遇到的困惑——这是新手很容易踩的**变量遮蔽(Variable Shadowing)**坑!咱们一步步来搞定它:
问题根源
你在类级别声明了code字段,但在Repeater1_OnItemCommand方法里又重新声明了一个局部变量Int32 code。这就导致你在方法里赋值的是这个临时的局部变量,而不是类级别的那个code字段。当方法执行完,局部变量被销毁,类的code还是初始的0,自然在button1_click里拿不到正确的值。
基础修复方案
只需要去掉方法里的Int32声明,直接给类的code字段赋值就行:
public partial class _Default : System.Web.UI.Page { // 类级别字段,初始化为0 Int32 code = 0; protected void Repeater1_OnItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "visitcode") { // 不要重新声明Int32,直接给类的code字段赋值 code = Convert.ToInt32(e.CommandArgument); } } protected void button1_click(object sender, EventArgs e) { string num = number.Value; string document = doc.Value; string format = "yyyy-MM-dd HH:mm:ss:fff"; string stringDate = DateTime.Now.ToString(format); // 现在就能拿到正确的code值了,注意转成string要加.ToString() string visitcode = code.ToString(); } }
额外提醒:Web Forms的回发特性
还有个很关键的点要注意:Web Forms页面每次回发(比如点击button)时,页面类会被重新实例化,类级别的字段会重置为初始值。如果你的Repeater1_OnItemCommand和button1_click是两次不同的回发操作,那上面的修改还是会失效。这种情况下,你需要用ViewState来跨回发保存值,示例如下:
public partial class _Default : System.Web.UI.Page { // 用ViewState封装字段,确保跨回发不丢失值 private Int32 Code { get { return ViewState["Code"] != null ? (Int32)ViewState["Code"] : 0; } set { ViewState["Code"] = value; } } protected void Repeater1_OnItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "visitcode") { Code = Convert.ToInt32(e.CommandArgument); } } protected void button1_click(object sender, EventArgs e) { string num = number.Value; string document = doc.Value; string format = "yyyy-MM-dd HH:mm:ss:fff"; string stringDate = DateTime.Now.ToString(format); string visitcode = Code.ToString(); } }
这样不管页面怎么回发,Code的值都会被保存在ViewState里,不会丢失。
内容的提问来源于stack exchange,提问作者zaknafein
相关产品推荐
相关产品推荐

