0% found this document useful (0 votes)
2 views2 pages

DataGridView SQL RowClick

This C# code defines a Windows Forms application that connects to a SQL database to display data from a 'Rooms' table in a DataGridView. It includes methods for loading data from the database and customizing the appearance of the DataGridView. Additionally, it handles cell click events to change the background and foreground colors of selected rows.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

DataGridView SQL RowClick

This C# code defines a Windows Forms application that connects to a SQL database to display data from a 'Rooms' table in a DataGridView. It includes methods for loading data from the database and customizing the appearance of the DataGridView. Additionally, it handles cell click events to change the background and foreground colors of selected rows.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

using System;

using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;

namespace DataGridDesign
{
public partial class Form1 : Form
{
SqlConnection connection = new SqlConnection(@"Data
Source=localhost;Initial Catalog=YourDatabaseName;Integrated Security=True");

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
LoadData();
CustomizeDataGrid();
}

private void LoadData()


{
try
{
connection.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Rooms",
connection);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
finally
{
connection.Close();
}
}

private void CustomizeDataGrid()


{
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor =
Color.DarkGreen;
dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Orange;
dataGridView1.DefaultCellStyle.SelectionForeColor = Color.White;
dataGridView1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.RowTemplate.Height = 30;
dataGridView1.BorderStyle = BorderStyle.None;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
}

private void dataGridView1_CellClick(object sender,


DataGridViewCellEventArgs e)
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor =
Color.Yellow;
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor =
Color.Black;
}
}
}

You might also like