2017-03-08 170 views
0

我有一个子类的按钮与一对夫妇性质对象倾斜访问类的属性

public class ZButton : Button 
{  
    private string UIB = "I"; 
    public int _id_ { get; set; } 
    public int rowIndex { get; set; } 
    protected override void OnClick(EventArgs e) 
    { 
     Form frmNew = new Form(UIB); 
     frmNew.ShowDialog(); 
     base.OnClick(e); 
    } 
} 

的我在窗体上放置该按钮,这里是在形式按钮的代码。

private void zButton1_Click(object sender, EventArgs e) 
    {   
     rowIndex = dataGridView1.CurrentRow.Index; 
     _id_ = Convert.ToInt16(dataGridView1["id_city", rowIndex].Value.ToString()); 

    } 

我不能访问这些属性(rowIndex位置)和(ID)和编译器会发出错误

The name 'rowIndex' does not exist in the current context 

我是相当新的C#,所以我必须失去了一些东西obviuos。

+1

完全不好的设计,定制控件显示表对话框取代

dataGridView1["id_city", rowIndex] 

... –

+1

'sender'是为其调用单击事件处理程序的按钮的实例。然而它是'object',所以你必须施放:'((ZButton)sender).rowIndex = ...'。在winforms中,每个控件都有名称,所以'zButton1.rowIndex = ...'也可以。 – Sinatr

回答

3

rowIndex_id_zButton的属性,它们不能直接在您的表单中访问。所以,如果你需要访问他们在点击事件,您必须将sender转换为zButton并访问instance.Something的性质是这样的:

private void zButton1_Click(object sender, EventArgs e) 
{ 
    zButton but=(zButton)sender;  
    but.rowIndex = dataGridView1.CurrentRow.Index; 
    but._id_ = Convert.ToInt16(dataGridView1["id_city",but.rowIndex].Value.ToString()); 
} 
0

投你的发件人按钮。

var button = sender as zButton; 
    if (button != null) 
    { 
     button.rowIndex ... 
     ... 
    } 
1

如果方法zButton1_Click是表单类的成员,则它可以直接访问它祖先类相同的类的属性,或者像您的按钮聚合对象的不性质。

为了访问您的按钮的属性,您应该明确指定您尝试访问哪个对象的属性。这意味着,如果你想访问一个聚合按钮zButton1的属性,你应该

dataGridView1["id_city", zButton1.rowIndex]