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

Customize DataGridView in C# WinForms

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)
11 views2 pages

Customize DataGridView in C# WinForms

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

using System;

using [Link];
using [Link];
using [Link];
using [Link];

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
{
[Link]();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Rooms",
connection);
DataTable dt = new DataTable();
[Link](dt);
[Link] = dt;
}
catch (Exception ex)
{
[Link]("Error: " + [Link]);
}
finally
{
[Link]();
}
}

private void CustomizeDataGrid()


{
[Link] =
[Link];
[Link] = [Link];
[Link] = false;
[Link] = [Link];
[Link] = [Link];
[Link] =
[Link];
[Link] = 30;
[Link] = [Link];
[Link] = [Link];
[Link] = false;
}

private void dataGridView1_CellClick(object sender,


DataGridViewCellEventArgs e)
{
[Link][[Link]].[Link] =
[Link];
[Link][[Link]].[Link] =
[Link];
}
}
}

Common questions

Powered by AI

The 'LoadData' method employs a try-catch-finally block for error handling. The try block contains code that might throw exceptions, such as opening the database connection or filling the DataTable. If an exception occurs, the catch block shows an error message using 'MessageBox.Show'. The finally block ensures that the 'connection.Close()' is executed regardless of an error, which is crucial for releasing resources and avoiding database lock issues .

The 'SqlConnection' is used to establish a connection to a SQL Server database. It is initialized with a connection string that specifies the data source as 'localhost', the initial catalog as 'YourDatabaseName', and uses integrated security. This connection is essential for executing SQL commands and retrieving data from the database to populate the DataGridView .

Setting 'MultiSelect' to 'false' is important when each operation is intended for a single data row, such as editing or deleting, ensuring that only one row can be interacted with at a time. This simplifies the interface and user operations, reducing the likelihood of errors when performing row-specific actions like updates .

Setting 'AutoSizeColumnsMode' to 'Fill' ensures that the columns in the DataGridView adjust their width so that the entire grid's width is fully utilized and no excess space remains. This setting eliminates horizontal scrolling, providing a neat and organized appearance of the data within available window space .

The 'CustomizeDataGrid' method enhances the DataGridView's interface by setting its header style to have a dark green background with white text, disabling the default visual styles for headers, and changing the selection colors to orange with white text. It also sets auto-size mode for columns, changes row height, removes the border, and configures full-row selection while disabling multi-selection. These adjustments improve readability and visual aesthetics of the grid .

The 'dataGridView1_CellClick' event alters the appearance of a row when it is clicked. It changes the clicked row's background color to yellow and the foreground color to black, providing visual feedback for user interaction. This customization enhances user experience by clearly indicating the selected row, which is particularly useful in data entry and review scenarios .

Setting 'SelectionMode' to 'FullRowSelect' ensures that clicking any cell within a row selects the entire row, rather than just individual cells. This improves the user experience by simplifying multi-cell data operations, such as copying, and is particularly useful in scenarios where row-related data needs to be treated as a single entity .

Creating 'DataGridViewCellStyle' objects allows for detailed customization of the DataGridView's appearance. The use of contrasting colors like dark green for headers and orange for selection provides a visually appealing design while ensuring readability. Such design choices adhere to UI principles of contrast and focus, enhancing user interaction and data visibility .

Disabling 'EnableHeadersVisualStyles' is necessary when you want custom styles to be applied to the DataGridView headers, rather than the default theme styles. In 'CustomizeDataGrid', this action allows for the specified back and fore colors to be applied to the headers, ensuring consistent styling that matches the application's aesthetic requirements, which would otherwise be overridden by Windows theme settings .

Data is loaded into the DataGridView by first opening the connection using 'SqlConnection.Open()'. The 'SqlDataAdapter' is then used to execute a SQL query ('SELECT * FROM Rooms') and fill a DataTable with the results. Finally, the DataGridView's 'DataSource' property is set to this DataTable to display the data. 'SqlDataAdapter' acts as a bridge between the DataSet and SQL Server, facilitating the retrieval and filling processes without using direct commands .

You might also like