简体   繁体   English

从另一个事件调用varialble

[英]calling varialble from another event

how I can call a variable ( private Label ccc; ) in another event: 在另一个事件中如何调用变量( private Label ccc; ):

private Label ccc;

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {

        Label Label1 = FindControlRecursive(Page, DropDownList1.SelectedValue) as Label;
        if (Label1 != null)
            this.ccc = lblCont;
            this.ccc.Text = Label1.Text;
    }


 public void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {


          this.ccc.Text = lblCont.Text;


            int bbb = Convert.ToInt32(lblCont.Text) - Convert.ToInt32(tbEnter.Text);
            if (bbb >= 0)
            {
                lblCont.Text = Convert.ToString(bbb);

            }
            else
            {
                ErrorDisplay.Text = "There are not enough tickets";
            }
        }
    catch (Exception ex)
    {
        ErrorDisplay.Text = ex.Message;
    }


}

I can not call this.ccc.Text = lblCont.Text; 我不能叫this.ccc.Text = lblCont.Text; in " public void btnSubmit_Clic k" 在“ public void btnSubmit_Clic k”中

It does (Object reference not set to an instance of an object.) 可以(对象引用未设置为对象的实例。)

Thakns!! Thakns!

Your ccc Label field must be assigned a value before you try to modify the .Text property. 在尝试修改.Text属性之前,必须为ccc标签字段分配一个值。 Since ccc is pointing to nothing you're getting that exception. 由于ccc没有指向任何内容,因此您将获得该异常。

Make sure that before the btnSubmit_Click function is called that the ccc field is assigned a Label object or assign it before doing anything inside the function. 确保在调用btnSubmit_Click函数之前,先对ccc字段分配一个Label对象,或者在对该函数进行任何内部操作之前对其进行分配。

In addition to Nick's answer: 除了尼克的答案:

The DropDownList1_SelectedIndexChanged event is not guaranteed to fire on every postback - if the user submits the page without changing the selection, this.ccc will be null. 无法保证DropDownList1_SelectedIndexChanged事件在每次回发时均会触发-如果用户提交页面而不更改选择,则this.ccc将为null。 Even if this.ccc was assigned in a previous postback, it will not be in the current one if the drop down list selection didn't change. 即使this.ccc是在上一个回发中分配的,如果下拉列表选择未更改,它也不会在当前回发中。

Hence why you need to make sure you assign it a Label instance somewhere else. 因此,为什么需要确保在其他地方为它分配Label实例。 For example in Page_Load or even in btnSubmit_Click just before your this.ccc.Text = lblCont.Text; 例如,在this.ccc.Text = lblCont.Text;之前的Page_Load甚至是btnSubmit_Click中; line. 线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM