How to Remove Columns From a Data Grid
- 1). Open Microsoft Visual Studio.
- 2). Click "File," and then select "New Project."
- 3). Double-click "Windows Forms Application" to create a new project. Visual Studio will display a new form named "Form1" in the editing window.
- 4). Click "File." Select "Toolbox" to open the toolbox. Locate "DataGridView" in the toolbox, and double-click that value. A new data grid control will appear on the form.
- 5). Return to the toolbox, and then double-click "Button." A button named "Button1" will appear on the form next to the data grid.
- 6). Locate the "TextBox" control in the toolbox. Double-click it to place it on the form next to the data grid and button.
- 1). Locate the word "Form1" in the form's title bar. Double-click "Form1." A code window will open and display the following code:
private void Form1_Load(object sender, EventArgs e)
{
} - 2). Paste the following code between the two brackets:
// Lines 1-3 System.Data.DataTable dataTable = new System.Data.DataTable();
dataTable.Columns.Add(new DataColumn("Name", typeof(string)));
dataTable.Columns.Add(new DataColumn("State", typeof(string)));
// Lines 4-5 dataTable.Rows.Add(new string[] { "Wilson", "Texas" });
dataTable.Rows.Add(new string[] { "Johnson", "Florida" });
// Line 6 dataGridView1.DataSource = dataTable;
This code creates a Data Grid that contains two rows and two columns. - 3). Right-click any area in the code window, and then select "View Designer." The designer window will reopen and display the form.
- 4). Double-click "Button1" to open its code window. The code will look like this:
private void button1_Click(object sender, EventArgs e)
{
} - 5). Paste the following code between the two brackets:
int tmp = Convert.ToInt16(textBox1.Text);
int columnToHide = tmp - 1;
dataGridView1.Columns[columnToHide].Visible = false;
The last line of code hides a column based on the value stored in "columnToHide." For instance, if "columnToHide" has a value of "one," the code will hide the data grid's first column. In this example, "columnToHide" gets its value from the value that you enter in the text box. - 6). Press "F5" to run the project. The form containing the button and data grid will appear. The data grid will contain data.
- 7). Enter a number between one and two in the text box, and click the form's button. The column number that you enter will disappear.
Create a Data Grid
Remove Columns
Source...