[英]C# Check if DataGridView Contains specific word
我目前正在開發一個 IRC 機器人。 發送的消息將顯示在 DataGridView 中。 所以現在我想檢查例如發送的消息是否包含特定的單詞。 讓我們說“測試”。
所以它應該檢查以下內容:
假設添加到 DataGridView 的發送消息是:我的名字是測試。
現在包含單詞“test”的單元格應該變成紅色。
我已經解決了這個問題,當消息只包含“測試”時。 但我真的不知道如何檢查句子中的單詞。
//編輯:我試過這個代碼:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[1].Value.ToString() == "test")
row.Cells["chat1"].Style.ForeColor = Color.Red;
//row.Cells["chat1"].Style.ForeColor = Color.CadetBlue;
}
親切的問候,馬克斯:)
檢查包含,以驗證字符串是否存在於給定輸入中。 您可以考慮在檢查Contains
之前確保應用ToLower
或ToUpper
方法,以確保獲得正確的結果
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[1].Value.ToString().Contains("test"))
row.Cells["chat1"].Style.ForeColor = Color.Red;
//row.Cells["chat1"].Style.ForeColor = Color.CadetBlue;
}
您也可以練習使用linq解決此問題
var items = this.dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => row.Cells[1].Value.ToString() == "Test");
foreach(DataGridViewRow row in items)
{
row.Cells["chat1"].Style.ForeColor = Color.Red;
}
這是一個老帖子,但我仍然可以用一些替代方法來填寫。 這工作得很好,沒有循環。 您確實需要選擇一個思路。
if (dgridvwListan.SelectedRows[0].Cells[2].Value.ToString() =="thewordincell")
dgridvwListan.SelectedRows[0].Cells[1].Style.BackColor = Color.Pink;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.