[WinForm Detailed Tutorial 7] DataGridView control in WinForm


DataGridView Is a control used in Windows Forms applications that displays data in the form of a grid (table). This control allows the user to define rows and columns, and corresponding cells. Core idea:

  • Rows: Horizontal sequence of data presentation.
  • Columns: Vertical sequence of data presentation.
  • Cells: The data storage unit at the intersection of rows and columns.

1.Main attributes

DataSource

DataSourceThe property is used to set the data source of the DataGridView control. Commonly used data source types are:

  • DataTable: Data table obtained from database query.
  • List<T>: Generic collection, where T is the type of the data model.
Row (Row related properties)
  • DataGridViewRow: Represents a row in the DataGridView control.
  • DataGridViewRowCollection: Represents the collection of all rows in the DataGridView control.
  • Rows: This property allows you to access or manipulate rows in a row collection.
Column (Column related properties)
  • DataGridViewColumn: Represents a column in the DataGridView control.
  • DataGridViewColumnCollection: Represents the collection of all columns in the control.
  • Columns: This property allows you to access or operate the columns in the column collection.
Cell (Cell related properties)
  • DataGridViewCell: Represents a cell in the DataGridView control.
  • Value: The actual data stored in the cell.
  • Selected: Indicates whether the cell is selected.
  • RowIndex: The row index where the cell is located.
  • ColumnIndex: The column index where the cell is located.
  • FormattedValue: The formatted value of the cell used for display.
Tombstone

In some business scenarios, row records are not actually deleted from the data source, but the status of the record is represented by modifying the value of the identification column (for example, 0 means normal, 1 means deleted).

AllowUserToAddRows

Controls whether blank lines for adding new lines are displayed.

  • True: Displays blank rows and automatically adds new blank rows as the user enters data. After completing the input, press Enter and the data will be added to the control.
  • False: Do not show blank lines for adding new lines.
AllowUserToDeleteRows

controls whether users can delete rows from DataGridView, default is true. The user can delete a row by selecting it and pressing the Delete key.

AllowUserToOrderColumns

Controls whether users are allowed to manually reposition columns.

  • True: Allows the user to reposition columns by dragging.
  • False: Does not allow users to manually adjust column positions.
Other layout and behavior properties
  • AllowUserToResizeColumns: Whether to allow users to resize column widths.
  • AllowUserToResizeRows: Whether to allow users to adjust row height.
  • AutoSizeColumnsMode: Determines the column's automatic sizing mode.
  • AutoSizeRowsMode: Determines the automatic sizing mode for rows.
  • EditMode: Defines when the contents of the cell can be edited.
  • GridColor: The color of the grid lines.
  • MultiSelect: Whether to allow users to select multiple cells, rows or columns at the same time.
  • SelectionMode: Set the cell selection mode.

2. Row, column and cell classes in the control

Properties of the DataGridViewColumn class
  • Name: Column name.
  • ColumnType: The type of column, such as DataGridViewTextBoxColumn, DataGridViewCheckBoxColumn, etc.
  • DataPropertyName: The property name bound to the data source.
  • HeaderText: The text displayed in the column header.
Properties of the DataGridViewRow class
  • DataBoundItem: The data object of the bound row.
  • Selected: Whether the row is selected.
  • State: Actual state, like DataGridViewElementStates.
  • Cells: A collection of cells in the row.
Properties of the DataGridViewCell class
  • Value: The actual value of the cell.
  • Selected: Whether it is selected.
  • RowIndex: The index of the row.
  • OwningRow: Owning row.
  • OwningColumn: Owning column.
  • ColumnIndex: The index of the column.
  • FormattedValue: Displays the formatted value.
  • FormattedValueType: The type of formatted value.
  • ValueType: The data type of the cell value.

3. A simple example, connecting to SQL database example

using System.Data;
using WinFormsTest.Helper;

namespace WinFormsTest
{
    public partial class frmDataGridView : Form
    {
        public frmDataGridView()
        {
            InitializeComponent();
        }

        private void frmDataGridView_Load(object sender, EventArgs e)
        {
            string sql = "select * from UserInfo";
            DataTable dt = DBHelper.GetDataTable(sql, 1);
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = dt;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
            string nameUser = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
            if (cell.FormattedValue.ToString() == "删除")
            {
                MessageBox.Show("删除了:" + nameUser);
            }
            else if (cell.FormattedValue.ToString() == "修改")
            {
                MessageBox.Show("修改了:" + nameUser);

            }
        }
    }
}

Insert image description here

4.DataGridView data source

  • DataGridView can bind different types of data sources, including DataTable, List<T>, BindingList<T>, etc.
  • When is bound to List<T>, each instance of T corresponds to one row of the DataGridView.
  • DataBoundItemThe attribute returns the object bound to the current row, for example, DataGridViewRow.DataBoundItem will return the corresponding object in the binding list.
Binding method
  1. DataTable:
    • When usesDataTable as the data source, each row of data is represented by the DataRow object.
    • For large amounts of data, DataTable may be a better choice because it has a lot of built-in support for data manipulation.
  2. List:
    • When usingList<T> as the data source, the data exists in the form of a list of objects.
    • For processing a collection of entity objects, especially when the amount of data is not large, List<T> is a suitable choice.
Optimization suggestions
  • It is recommended to useDataTable when the amount of data is large, because it is designed to handle large batches of data.
  • For small amounts of data or when complex objects need to be represented, List<T> is more suitable because it can be directly bound to the properties of the object.
  • SqlDataReader only reads one row of data at a time, and it is forward-only, which is suitable for reading large batches of data. However, in Windows Forms, the data of SqlDataReader is directly converted to List<T> before binding to DataGridView will be more flexible.

[WinForm Detailed Tutorial] How to obtain source code

Insert image description here

Excellent recommendations:
[C# Advanced 1] Array (Array), collection (ArrayList, Queue, Stack, HashList), List
[C# Advanced 8] Serialization and deserialization in C# (binary serialization, XML serialization and JSON serialization) a>

[Advanced C#] Summary of some common knowledge points in C# syntax
[WinForm detailed tutorial 1] Form, Label, TextBox and Button controls, RadioButton and CheckBox, ListBox
[WinForm detailed tutorial three] NumericUpDown, PictureBox, RichTextBox and three Timer controls in WinForm
[WinForm detailed tutorial four] ProgressBar and ImageList in WinForm and ListView control
[WinForm detailed tutorial five] MenuStrip, ContextMenuStrip, ToolStrip, StatusStrip control in WinForm
[WinForm detailed tutorial six] GroupBox and Panel in WinForm , TabControl, SplitContainer control
[C# Advanced] Delegates, events, callback functions, anonymous functions and lambda expressions in C#

If you are interested in the intelligent construction major, or are a student, teacher or practitioner in a related field, you are welcome to join us through the WeChat public account [Intelligent Construction Xiaoshuo]!

Insert image description here
Hope it helps, and welcome to follow us. More related content will be updated later!

Guess you like

Origin blog.csdn.net/QH2107/article/details/134217550