I have a windows form application where it contains a datagridview that reads data from another application.
My datagidview is not bound to a DB.
Now, would like to make my datagridview expand and collapse during the run time. Means that, I need first three columns visible when the app starts and a small control button on the datagridview enables the user to display the rest invisible columns. Once the + clicked, the datagridview will display the invisible columns and once clicked again (-), the columns will be back to invisible status.
How can I achieve that? This is my code, but looks like still incomplete, Also, I don’t want to use a columns to expand/collapse but maybe a button attached on the top corner of the datagridview would be better to be used?
private void mydataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == this.ColumnButton.Index)
{
bool visible = !this. EmployeeAge.Visible;
this.EmployeeAge.Visible = true;
this.EmployeeSal.Visible = true;
this.Location.Visible = true;
this.MobileCol.Visible = true;
this.ColumnButton.HeaderText = visible ? "-" : "+";
Syed ShanuPosted Apr 6, 2015, 1:39 AM
Check the Attached Sample Source Program hope that will help you.
In your windows form place a button and one Datagridview.
In Form Load
private void Form1_Load(object sender, EventArgs e)
{
button1.Text = "+";
DataTable DTable = new DataTable();
//ServersTable - DataGridView
for (int i = 1; i <= 6; ++i)
{
DTable.Columns.Add(new DataColumn("Col"+i));
}
for (int i = 0; i < 7; ++i)
{
DataRow r = DTable.NewRow();
r.BeginEdit();
foreach (DataColumn c in DTable.Columns)
{
r[c.ColumnName] = "Rows "+i;//writing values
}
r.EndEdit();
DTable.Rows.Add(r);
}
dataGridView1.DataSource = DTable;
showHideColumns(false);
}
IN Button Click
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "+")
{
button1.Text = "-";
showHideColumns(true);
}
else
{
button1.Text = "+";
showHideColumns(false);
}
}
Show and Hide Datagridview Column
private void showHideColumns(Boolean colHideStatus)
{
dataGridView1.Columns[0].Visible = colHideStatus;
dataGridView1.Columns[1].Visible = colHideStatus;
dataGridView1.Columns[2].Visible = colHideStatus;
}
Eline SamiPosted Apr 6, 2015, 5:44 AM