![](/img/trans.png)
[英]How to check if a cell in selected row in dataGridView is empty/null, using C#?
[英]How to check if a selected row in a datagridview is empty(has no item) C#
我如何檢查行的單元格中是否有數據,即不是空/空。
我一直在嘗試以下方面:
if (dgvClient.SelectedRows.Count > 0)
{
DataGridViewRow currentRow = dgvClient.SelectedRows[0];
if (currentRow.Cells.ToString() != String.Empty)
{
//The code that will be here will open a form
}
else
{
MessageBox.Show("Select a non null row");
}
}
但是,它似乎沒有工作,我沒有想法:/
感謝您的幫助,Ari
.Cells
是DataGridViewCell
對象的集合。
您需要遍歷該集合並測試每個單元格以查看它是否具有值...
if (currentRow.Cells.Count > 0)
{
bool rowIsEmpty = true;
foreach(DataGridViewCell cell in currentRow.Cells)
{
if(cell.Value != null)
{
rowIsEmpty = false;
break;
}
}
if(rowIsEmpty)
{
MessageBox.Show("Select a non null row");
}
else
{
//DoStuff
}
}
另一種檢查是否選擇了新空行的方法
if(dataGridView.CurrentRow.Index == dataGridView.Rows.Count -1)
{
//you selected a new row
}
驚訝沒有linq回答所以這里是:
if (dataGridView1.Rows.Cast<DataGridViewRow>()
.Any(x => x.Cells.Cast<DataGridViewCell>()
.Any(c => c.Value != null)))
DataGrid行是DataCollection類型,它實現IEnumerable。 你只需要投射單元格和行。
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
DataGridViewCell cell = dataGridView1[j, i];
object value = cell.Value;
if (value == string.Empty)
{
//do
}
}
}
我認為這可以通過處理DataGridView.RowEnter事件來完成。 當行接收輸入焦點但在它成為當前行之前,會發生RowEnter事件。 例如,從一個單元格移動到另一行中的另一個單元格。
檢查每個單元格值:
void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ReadOnly = checkrow(dataGridView1.Rows[e.RowIndex]);
}
bool checkrow(DataGridViewRow testrow)
{
for (int i = 0; i < testrow.Cells.Count; i++)
{
if (testrow.Cells[i].Value != null)
{
// if datagridview is databound, you'd better check whether the cell value is string.Empty
if (testrow.Cells[i].Value.ToString() != string.Empty)
{
// if value of any cell is not null, this row need to be readonly
return true;
}
// if there is an unbound checkbox column, you may need to check whether the cell value is null or false(uncheck).
}
}
// else false
return false;
}
我有同樣的問題來檢查C#窗體中當前行是否為空,我把以下邏輯對我有用,如果要檢查所有值然后將所有單元格值放置為0,也可以使用它1,2,3 ...或創建一個動態函數來檢查它。
private void dataGridViewProduct_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (dataGridViewProduct.Rows[e.RowIndex].Cells[0].Value.ToString()!= string.Empty)
{ //dowork
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.