Skip to main content
 首页 » 编程设计

c#之如何使用 Sqlite 数据库在 C# 中通过单元格的值更改特定的数据网格单元格属性

2024年02月23日15shangdawei

我是 c# 和 Database 链接的新手,这就是为什么无法通过搜索 stackoverflow 的旧帖子来获得它的原因

代码如下

private void bookDetails() 
    { 
        string connectionPath = @"Data Source=Data\libraryData.dat;Version=3;New=False;Compress=True"; 
 
        using (SQLiteConnection connection = new SQLiteConnection(connectionPath)) 
        { 
            SQLiteCommand command = connection.CreateCommand(); 
            connection.Open(); 
            string query = "SELECT bookno as 'Book No.', bookCode as 'ISBN No.', title as 'Title', author as 'Author', publisher as 'Publishers', edition as 'Edition', storagehint as 'Storage Hint', description as 'Description' FROM booksDetails"; 
            command.CommandText = query; 
            command.ExecuteNonQuery(); 
 
            SQLiteDataAdapter da = new SQLiteDataAdapter(command); 
            DataSet ds = new DataSet(); 
            da.Fill(ds, "booksDetails"); 
            int c = ds.Tables["booksDetails"].Rows.Count; 
            dataGridView1.DataSource = ds.Tables["booksDetails"]; 
            dataGridView1.Sort(dataGridView1.Columns["ISBN No."], ListSortDirection.Ascending); 
            dataGridView1.ReadOnly = true; 
            connection.Close(); 
            this.Totals.Text = "Total No. of Books Found : "+ Convert.ToString(c); 
        } 
    } 

我像上面那样使用获取一些图书馆书籍的详细信息,现在我想突出显示一个特定的单元格或通过值 no 更改它的颜色。书或任何其他..

首选示例代码

提前致谢...

请您参考如下方法:

您需要遍历 datagridview 中的行,然后将颜色设置为适当的行。

假设颜色根据某些条件发生变化,

private void myDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
  { 
   int colIndex = e.ColumnIndex; 
   int rowIndex = e.RowIndex; 
 
   if (rowIndex >= 0 && colIndex >= 0) 
   { 
    DataGridViewRow myRow = dataGridView1.Rows[rowIndex]; 
    if (myRow.Cells[colIndex].Value.ToString() == "High") 
    myRow.DefaultCellStyle.BackColor = Color.Red; 
   } 
  }