Is it possible in a single hit to remove all columns from a datagrid?
I know I could loop though and remove them one by one, or remove the whole thing and create it.
But it is possible to simply clear columns and leave the grid in place so users can start fresh.
i.e. put it back to its original state.
OK here is the code I have
private void PopulateGrid()
{
UserVGrid.AutoGenerateColumns = false;
UserVGrid.Columns.Clear();
List<string> _values = populate.GetVaribles;
foreach (var line in _values)
{
if (!line.Contains("Startind"))
{
string[] newline = line.Split('=');
DataGridViewColumn newColumn = new DataGridViewTextBoxColumn();
newColumn.Name = newline[0];
newColumn.HeaderText = newline[1];
newColumn.ToolTipText = newline[2];
UserVGrid.Columns.Add(newColumn);
}
}
so lets assume _values has apple, pear as values
running this method once and i get a datagrid with two colums named apple and pear.
running it a second time this time with _values containg char , table.
And i end up with 4 colums apple, pear, chair and table. What I want is the second time it is run it clears the grid fist and then applied the new colums.
Cheers
Aaron
The DataGridView columns collection has a Clear() method.
dataGridView1.Columns.Clear();
This doesn't work with a bound datagridview and autogenerated columns - in that case simply replace the datasource with null or with an empty datasource:
dataGridView1.DataSource = null;
or turn off autogeneration and create the columns in code:
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
dataGridView1.Columns.Add(col);
These manually generated columns will be removed by the Clear() method.
Here's what worked for me
List<string> lstOverride = new List<string>();
lstOverride.Add("IssuerOnly");
lstOverride.Add("TickerOnly");
lstOverride.Add("All");
lstOverride.Add("Private Equity");
lstOverride.Add("Ignore");
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.HeaderText = "Override";
cmb.Name = "cmb";
cmb.DataSource = lstOverride;
cmb.DataPropertyName = "Override";
dgvWebData.Columns.Add(cmb);
I added a DataGridViewComboBoxColumn and had set the DataPropertyName of it to the column I needed to have the drop down.
Clear the datatable
If ds.Tables.Count > 0 Then
ds.Tables(0).Columns.Clear()
ds.Tables(0).Rows.Clear()
End If
and set the datagridview datasource to nothing
dg.DataSource = Nothing
for removing a columns of dataGridView you can do like that "P_Comment" is Columns Name
dataGridView1.Columns.Remove("p_Comment");
and for remove all columns you can use
dataGridView1.Columns.Clear();
This allowed me to delete all the data and the column headers from a datagridview
ds2.Tables.Clear();
dataGridView1.DataSource = null;
dataGridView1.Columns.Clear();
Related
I Have requirement to fill the datagridview row by row . i.e. if 3rd row is currently selected then data needs to be filled in 3rd row (my query returns always single row ) . same for every row.
some what like
DataTable dt = new DataTable();
dataadapter.Fill(dt);
dataGridView1.Rows[index].DataSource = dt; (just a hunch, but not working)
(instead of ) //dataGridView1.DataSource = dt;
hope that I made my requirement clear to you
Is their any way to accomplish it ....
Thanks in advance....
If your query returns a single row then you just have to fill the columns with correct values from your query:
dataGridView1.Rows[rowIndex].Cells["ColumnName"].Value =
dt.Rows[0]["ColumnNameInDataTable"].ToString();
Your grid will not be bound to the data this way. But it will fill the columns in the current row like you've asked.
I don't think this is possible directly,
You could use a List with a certain amount of empty objects and bind this List to your DataGridView... Then you would have empty Rows to work with. You can then fill single rows of the List with data and update the binding.
I also think you need a BindingSource and not a DataTable in this case...
Something like this:
private List<YourObject> gridData; // List
private BindingSource bindingSource;
public void Init()
{
this.gridData = new List<Anything>();
//prefill list, in this case we want to have 100 empty rows in DataGrid
for (var i = 0; i < 100; i++)
{
this.gridData.Add(new YourObject());
}
this.bindingSource.DataSource = this.gridData;
}
public void UpdateRow(int row)
{
this.gridData[row] = (from .. in select ...).FirstOrDefault(); // your query
}
In my WinForms application I'm populating two DataGridView's like below;
private void PopulateData()
{
//Load data
DataTable dtAll = LoadData();
DataTable dtSelected = dtAll.Clone();
dtAll.PrimaryKey = new DataColumn[] { dtAll.Columns["PK"] };
dtSelected.PrimaryKey = new DataColumn[] { dtSelected.Columns["PK"] };
DataView leftGridView = new DataView(dtAll);
DataView rightGridView = new DataView(dtSelected);
dgvLeft.AutoGenerateColumns = false;
dgvLeft.DataSource = leftGridView;
dgvRight.AutoGenerateColumns = false;
dgvRight.DataSource = rightGridView;
}
Then in some other place I'm exchanging columns between two DataGridView like below;
private void ExchangeData()
{
//Get current row of left grid
DataRow selectedRow = ((DataRowView)dgvLeft.CurrentRow.DataBoundItem).Row;
//Find the row from all data table
DataRow foundRow = dtAll.Rows.Find(selectedRow["PK"].ToString());
if (foundRow == null)
return;
//Exchange row between grids
dtAll.Rows.Remove(foundRow);
dtSelected.ImportRow(foundRow);
}
But only dtAll.Rows.Remove(foundRow); is completing correctly and reflected in the DataGridView but the line dtSelected.ImportRow(foundRow); doesn't add the row to dtSelected. I changed this line to dtSelected.ImportRow(selectedRow); but the result is same. Any thoughts?
In MSDN something catches my attention was;
If the new row violates a Constraint it won’t be added to the data
table.
Note: This question is not related to following SO posts;
DataTable.ImportRow is not adding rows
Why DataTable.Rows.ImportRow doesn't work when passing new created DataRow?
DataTable importRow() into empty table
ImportRow is not working
EDIT: I added the PrimaryKey part, DataView and DataRowCollection.Find method later to incorporate some filtering feature. Without these the code worked as intended.
Another EDIT: I removed the PrimaryKey part from PopulateData method and modified the ExchangeData method as follows;
//Get current row of left grid
DataRow selectedRow = ((DataRowView)dgvLeft.CurrentRow.DataBoundItem).Row;
//Find the row from all data table
int foundRow = dtAll.Rows.IndexOf(selectedRow);
//Exchange row between grids
dtAll.Rows.RemoveAt(foundRow);
dtSelected.ImportRow(selectedRow);
But the issue is same.
OK then it was because of my order of the code to execute. Let me explain.
This was the code I execute for the exchange;
//Exchange row between grids
dtAll.Rows.RemoveAt(foundRow);
dtSelected.ImportRow(selectedRow);
Here the row is first deleted before it's been imported to the dtSelected table. That's why dtSelected never got the row imported whatever the way I tried.
So changing the order of the code fixes my issue;
//Exchange row between grids
dtSelected.ImportRow(selectedRow);
dtAll.Rows.RemoveAt(foundRow);
The fear emotion in Inside Out says a phrase which suites this situation. "My Bad"
I'm using MySQL .net connector to fill a Datagridview using Mysqladapter and Datagridview.Bindingsource. That works good, but I want to change one thing:
In the table which is filled to the DataGridview, there is a column with a text type. The cells in this columns are displayed as a Datagridviewtextboxcell in the datagridview, but I want to change it to DataGridviewComboboxCell (the users should select between ~10 items).
I already tried a lot but nothing worked as it should. The Columns in the DataGridview are readonly, I cannot change DefaultCellTemplate to a DataGridviewComboboxCell, cause it doesn't inherit DataGridviewTextboxcell.
I also tried this: Gridview - convert textboxcell to comboboxcell and back and I think my problem could be solved over this way, but with this solution I have also 1 problem: It doesnt show a DropDown Button.
Any help will be greatly appreciated.
To do this you need to add a new DataGridViewComboBoxColumn to the grid and then hide the text box column.
I show this using code below but you can do the same using the designer (just set the properties I set in code using the designer).
The key things to note are:
DataPropertyName refers to a property of the grid's data source - likely your text box source
You need to provide the column with its own data source
DisplayMember and ValueMember refer to the data source of the column
Here is the code to add the column:
// Here I do this in the form constructor - there are other places you can do it
public Form1()
{
InitializeComponent();
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
// You need to set some properties on the column to make it work
// Datasource is the source (usually a list) of objects to show in the combobox
col.DataSource = dataSource;
col.DataPropertyName = "ColumnInGridDataSource";
col.DisplayMember = "DisplayProperty";
col.ValueMember = "ValueProperty";
dataGridView1.Columns.Add(col);
// This hides the textboxcolumn
dataGridView1.Columns["YourTextBoxColumnName"].Visible = false;
}
In the answer you linked, before the line:
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] = cb;
Try adding:
cb.DisplayStyle = DataGridViewComboBoxDisplayStyle.CHOOSE_ONE;
cb.FlatStyle = FlatStyle.CHOOSE_ONE;
I am not sure how exactly you want to style your comboboxes, so instead of "CHOOSE_ONE", try out the styles and pick the style you want.
Edit: Seems like you're not changing it to a combobox at all. Try this:
var values = new List<string> { "a", "b", "c" };
var cell = new DataGridViewComboBoxCell();
cell.DataSource = values;
dataGridView1[col, row] = cell;
I have a DataGridView and I am populating it through a DataTable. On initializing, I add DataColumns to the DataTable and then set the DataSource of the DataGridView to the DataTable. Here is the code:
DataTable mTable = new DataTable("Test");
DataColumn col = new DataColumn;
col.DataType = System.Type.GetType("System.Boolean");
col.ColumnName = "First";
col.ReadOnly = false;
mTable.Columns.Add(col);
col = new DataColumn;
col.DataType = System.Type.GetType("System.String");
col.ColumnName = "Second";
col.ReadOnly = false;
mTable.Columns.Add(col);
this.myGridView.DataSource = mTable;
This works fine however, I want to make one of the columns showup as a combobox. I think I have to do something with the Column's datatype but I am not sure how to do this. Can anyone give me any pointer towards this?
This is old, but I thought I'd try to answer it anyways since I had the same question myself a while ago.
First of all, you cannot make a DataTable column of type DataGridViewComboBoxColumn. DataColumn inherits from System.Data, while DataGridView*Columns inherit from System.Windows.Forms.
What you can try is this: Once your DataTable is bound to your DataGridView, the columns from the DataTable should show up on the DataGridView in the designer. If you then expand the Columns property of your DataGridView, you should see your columns from your DataTable have been added to the list. Select the column that you want, and in the right-hand pane there will be a property called 'ColumnType'. The default type is DataGridViewTextBoxColumn, but you can change it to DataGridViewComboBoxColumn.
change the declaration to this:
DataGridViewComboBoxColumn column1 = new DataGridViewComboBoxColumn()
I have a DataTable as a data source of a GridView. I'm adding a combo box the the GridView .
I'd like to be able to add a column to the DataTable that would automatically update with the value the user selects in the GridView. Can anyone help?
and the answer is...
DataTable myTable = getYourDataByMagic();
DataGridViewComboBoxColumn box = new DataGridViewComboBoxColumn();
BindingSource bs = new BindingSource();
bs.add("choice one");
bs.add("choice two");
box.HeaderText = "My Choice";
box.Name = "select";
box.DataSource = bs;
box.DataPropertyName = "select";
myTable.Columns.Add(new DataColumn("select"));
this.dataGridView1.Columns.Add(box);
this.dataGridView1.DataSource = myTable;
now, your "myTable" will update with the values selected in the combobox
I'd put two grids side by side one containing all info and one that just had the blank column. I would update the datatable with the grid that contained the one column. This would be update based on selected index of the previous grid. First thing to come to mind.