[英]Loop based on null value of DataGridView cell
我對使用 c# 還是個新手。我在論壇中搜索了很多主題,但找不到解決方案。 如果您能提供幫助,我將不勝感激。
我無法解決的問題; 如果 dataGridView2.Rows[i].Cells[5] value=null 或為空,則運行以下代碼。
如果它已滿,我希望它遞增 [i] 並移至下一行。
循環停止點=DataGridView的列長
for (int i = 0; i < **???**; i++)
{
if (**???**)
{
TxtSayKod.Text = dataGridView2.Rows[i].Cells[2].Value.ToString() + dataGridView2.Rows[i].Cells[10].Value.ToString();
TxtHome.Text = dataGridView2.Rows[i].Cells[3].Value.ToString();
TxtAway.Text = dataGridView2.Rows[i].Cells[10].Value.ToString();
button1.PerformClick();
Thread.Sleep(3000);
btnupdate.PerformClick();
}
...
}
您可以使用 foreach 循環來簡化循環
foreach (DataGridViewRow row in dataGridView2.Rows)
{
if (row.Cells[5].Value is null) // Remove this: ;
{
string away = row.Cells[10].Value.ToString();
TxtSayKod.Text = row.Cells[2].Value.ToString() + away;
TxtHome.Text = row.Cells[3].Value.ToString();
TxtAway.Text = away;
button1.PerformClick();
Thread.Sleep(3000);
btnupdate.PerformClick();
}
}
即使在使用 for 語句時,您也可以將當前行分配給一個變量以簡化以下代碼:
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
var row = dataGridView2.Rows[i];
if (row.Cells[5].Value is null)
{
string away = row.Cells[10].Value.ToString();
...
}
}
請注意,test is int
僅在值已作為int
分配給單元格而不是number.ToString()
時才有效。 否則,如果它是字符串,測試:
if (row.Cells[3].Value is null or string { Length: 0 })
這使用類型模式后跟屬性模式。 請參閱: C# 8.0 中的模式匹配
if (**???**);
之后的分號 (;) (在未經編輯的問題中)終止 if 語句。 刪除它必須將以下代碼塊作為 if 的一部分執行。
這樣做,對所有行運行一個循環並檢查相應的單元格。
foreach (DataGridViewRow row in dataGridView2.Rows)
{
if (row.Cells[5].Value is not null && row.Cells[5].Value.ToString() == string.Empty)
{
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.