2017-03-08 145 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]