2015-10-16 97 views
1

我已經以編程方式將登錄按鈕添加到DataGridView。我想檢查來自數據庫的字段登錄時間,如果它是空的按鈕名稱應該是login否則它的名字應該是logout如何動態添加按鈕名稱和文本到gridview按鈕?

private void frmAttendance_Load(object sender, EventArgs e) 
{ 
    GetData();//Fetch data from database 
    DataGridViewButtonColumn buttonLogin = new DataGridViewButtonColumn(); 
    buttonLogin.Name = "Login"; 
    buttonLogin.Text = "Login"; 
    buttonLogin.UseColumnTextForButtonValue = true; 
    dataGridView1.Columns.Add(buttonLogin); 
    // Add a CellClick handler to handle clicks in the button column. 
    dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick); 
} 
+0

嗨,歡迎來到SO!請告訴我們你到目前爲止做了什麼,請閱讀[this](http://stackoverflow.com/help/how-to-ask) – jomsk1e

+0

我編輯了答案,現在只用第一部分就足夠了。 **要添加按鈕列,您可以**。僅當您需要爲按鈕設置不同的文本時才使用第二部分。希望你找到更新有用:) –

回答

2

要添加一個按鈕欄,您可以:

var button=new DataGridViewButtonColumn(); 
button.Name="LoginButton"; 
button.HeaderText="Login"; 
button.Text = "Login"; 
button.UseColumnTextForButtonValue = true; 

this.dataGridView1.Columns.Add(button); 

要設置按鈕欄的文本動態

要顯示每個按鈕上「登錄」的文字,它足以設置:

button.Text = "Login"; 
button.UseColumnTextForButtonValue = true; 

此外,如果你需要設置按鈕不同的文字,你可以使用CellFormatting事件的DataGridView和設置這些細胞的值:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    //If this is header row or new row, do nothing 
    if (e.RowIndex < 0 || e.RowIndex == this.dataGridView1.NewRowIndex) 
     return; 

    //If formatting your desired column, set the value 
    if (e.ColumnIndex=this.dataGridView1.Columns["LoginButton"].Index) 
    { 
     //You can put your dynamic logic here 
     //and use different values based on other cell values, for example cell 2 
     //this.dataGridView1.Rows[e.RowIndex].Cells[2].Value 
     e.Value = "Login"; 
    } 
} 

你應該這樣分配處理程序CellFormating事件:

this.dataGridView1.CellFormatting += dataGridView1_CellFormatting; 
+0

@ user3089887 LoginTime如何可以相關**如何動態添加按鈕名稱和文本到gridview按鈕?** –

+0

@ user3089887你不需要該列在dataGridView中訪問它。例如,您可以通過單元格格式化事件'dataTable1.Rows [e.RowIndex] [5]'以這種方式訪問​​它,在數據表中使用該列的索引,結果也是對象,您可以將其轉換爲'DateTime'或使用'ToString()' –

+0

@ user3089887歡迎您:) –

1

你可以去hrough的DataGridView在一個循環:

foreach(DataGridViewRow row in dataGridView1.Rows) 
{ 
    DataGridViewCell cell = row.Cells[0] //Button column index. 
    //Put your data logic here. 
    cell.Value = "Login"; 
} 

但在這種情況下,你必須知道的C你的Olumn Index DataGridViewButtonColumn

+0

非常簡單且很好用,但不支持新添加的行,如果您想要設置基於其他單元格值的按鈕值,則不能更新,而其他單元格值變化。 +1 :) –

+0

我沒有在dataGridview中獲取loginTime,所以加載datagridview時怎麼做。 –

+0

我認爲@RezaAghaei答案可能更適合你。由於我的方法只能在datagridview加載後運行,並且不會再改變它。否則,我需要您在載入loginTime時的更多信息。 – Huntt