2016-11-26 66 views
0
foreach (DataGridViewRow dgvr in dataGridViewProductList.Rows) 
       { 
        string dgvrID = dgvr.Cells["ID"].Value.ToString(); 
        DataRow[] s = DT.Select("BillID = " + dgvrID); 
        if (s.Length > 0) 
        { 
         dataGridViewProductList.Columns["chk"].ReadOnly = false; 
         dataGridViewProductList.Rows[dgvr.Index].Cells["chk"].ReadOnly = false; 
         dataGridViewProductList.Rows[dgvr.Index].Cells["chk"].Value = 1; 
     } 
    } 

選中狀態不改變爲選中,我怎樣才能改變如何更改DataGridViewCheckBoxCell運行的代碼<code>DataGridViewCheckBoxCell</code>後代碼

我試圖

DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)dataGridViewProductList.Rows[dgvr.Index].Cells["chk"]; 
         cell.ReadOnly = false; 
         cell.TrueValue = true; 

         cell.Value = cell.TrueValue; 

但不工作的選中狀態。

+0

'cell.Value = CheckState.Checked;'' – bansi

+0

= cell.Value CheckState.Checked;'它不工作對我來說@bansi –

+0

價值爲布爾類型:'.value的= TRUE' – Slai

回答

1

一個建議是試試這個。在設置true/false值之前,請檢查cell.Value是否爲空。如果是,則將其設置爲cell.Value = true; or cell.Value = false; NOT cell.Value = cell.TrueValue/FalseValue;下面的代碼應該在按鈕單擊時切換(檢查/取消選中)列3中的每個複選框。如果該複選框爲空,則將其設置爲true。如果我在使用cell.Value = cell.TrueValue;時發現它不起作用。

只是一個想法。

private void button1_Click(object sender, EventArgs e) 
{ 
    foreach (DataGridViewRow row in dataGridView1.Rows) 
    { 
    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells[2]; 
    if (cell.Value != null) 
    { 
     if (cell.Value.Equals(cell.FalseValue)) 
     { 
     cell.Value = cell.TrueValue; 
     } 
     else 
     { 
     cell.Value = cell.FalseValue; 
     } 
    } 
    else 
    { 
     //cell.Value = cell.TrueValue; // <-- Does not work here when cell.Value is null 
     cell.Value = true; 
    } 
    } 
} 

一個更緊湊的版本切換複選框值 - 假值刪除檢查。

if (cell.Value.Equals(cell.FalseValue)) 

這是否永遠不會進入,因爲沒有選中將返回一個空cell.Value,這將因此由先前的if(cell.Value != null)被抓的複選框。換句話說......如果它不是空的......它被檢查。

private void button1_Click(object sender, EventArgs e) 
{ 
    foreach (DataGridViewRow row in dataGridView1.Rows) 
    { 
    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells[2]; 
    if (cell.Value != null) 
    { 
     cell.Value = cell.FalseValue; 
    } 
    else 
    { 
     //cell.Value = cell.TrueValue; // <-- Does not work here when cell.Value is null 
     cell.Value = true; 
    } 
    } 
} 

希望這會有所幫助。