How to empty a datagridview? - c#

I don't know what is the syntax for emptying a datagridview. Please help me here is my code.
if (cboProduct.SelectedIndex != -1)
load_variant();
else
//empty the datagridview
cboProduct.SelectedIndex = -1;

set datasource as null
dataGridView1.DataSource = null;
Or
dataGridView1.Rows.Clear()
OR
while (dataGridView1.Rows.Count > 0)
{
dataGridView1.Rows.RemoveAt(0);
}

syntax for emptying a datagridview
Just assign null to its DataSource property.
yourGridView.DataSource = null;

Just set DataGridView.DataSource property to null
Gets or sets the data source that the DataGridView is displaying data
for.
DataGridView1.DataSource = null;
As an alternative (not exactly what .DataSource = null does)
DataTable dt = (DataTable)DataGridView1.DataSource;
if(dt != null)
dt.Clear();

You can set its DataSource to null :
dataGridView.DataSource = null;

Approach 1:
datagridview1.DataSourse=null;
Approach2:
DataView DV = (DataView)this.SqlDataSource1.Select(DataSourceSelectArguments.Empty);
DV.Table.Clear();
Approach 3:
datagridview1.DataSource = ""
Approach 4:
datagridview1.Dispose();//Clears gridview with all its properties
Approach 5:
Using Javascript:
document.getElementById("datagridview1").outerHTML = "";
Hope Its Helpful.

if (dgView.DataSource == null) return;
((DataTable)dgView.DataSource).Rows.Clear();
((DataTable)dgView.DataSource).Columns.Clear();
I used this one to clean datagrid view on my window application.
dgView.DataSource = null is not working for me

Setting the data source to null will also reset all formatting of the DataGridView. You can preserve the formatting by creating an empty DataTable and setting that as the source.
For example:
// Create an empty datatable
DataTable empty = new DataTable();
empty.Columns.Add("Name", typeof(string));
empty.Columns.Add("Color", typeof(myEnum));
empty.Columns.Add("Count", typeof(int));
...
// Clear datagridview
dgv.DataSource = empty;

Try this:
int nn = yourgridview.Rows.Count;
for (int i=nn; i>1; i--)
{
{
yourgridview.Rows.RemoveAt(i-2);
}
}

Related

From Datagridview to other datagridview add under older rows

I have little problem , I shared images and code below.
I have two datagridview in my code block. First(left side in form) datagridview's name searchDataGridView. This grid shows data from my database by some filters. Second(right side in form) datagridview's name dataGridView1. This grid shows when I click next button if I select some rows from first grid then this rows will add to dataGridView1. This code block working very well but this that my problem when I click next button and selected rows and added to dataGridView1 then searchDataGridVÄ°ew will show new items and selected rows will add to datagridView1, but when I add new items to dataGridView older rows will clear and new selected rows will add but I need that news selected rows must add to under older rows. Thank you for helping.
private void buttonNext_Click(object sender, EventArgs e)
{
Search searchObj = new Search();
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Company");
dt.Columns.Add("Category");
dt.Columns.Add("Price");
foreach (DataGridViewRow drv in searchDataGridView.Rows)
{
bool chkboxselect = Convert.ToBoolean(drv.Cells["CheckBox"].Value);
if (chkboxselect)
{
dt.Rows.Add(drv.Cells[2].Value, drv.Cells[3].Value, drv.Cells[4].Value, drv.Cells[8].Value);
drv.DefaultCellStyle.BackColor = Color.Gray;
drv.DefaultCellStyle.ForeColor = Color.Aqua;
}
dataGridView1.DataSource = dt;
}
counter +=1;
if (counter == maxIndex)
{
counter =0;
}
try
{
searchCategoryComboBox.SelectedIndex = counter;
}
catch (System.ArgumentOutOfRangeException) // CS0168
{
MessageBox.Show("hata yakalandı");
return;
}
//catch for error outofrange
searchCategoryComboBox.SelectedIndex =counter;
searchObj.Company = searchCompanyComboBox.Text;
searchObj.Category = searchCategoryComboBox.Text;
SearchManager searchMangObj = new SearchManager();
DataTable dt2 = searchMangObj.SearchInfo(searchObj);
searchDataGridView.DataSource = dt2;
textBox1.Text = String.Empty;
}
The problem is the way you get data from the db:
DataTable dt2 = searchMangObj.SearchInfo(searchObj);
searchDataGridView.DataSource = dt2;
Your SearchInfo method returns a new datatable and you bind that so the rows from the previous table are lost. Modify this method so it takes a datatable as a parameter (ie the existing datatable) and add rows to it.
You didn't say how your SearchInfo works to get rows from the db, but I suspect it will use a dataadapter or tableadapter, in which case you should set its ClearBeforeFill property to false to stop it from clearing the search datatable (the table that is databind'd to the searchdatagridview.DataSource)
You would then use it like:
searchMangObj.SearchInfo(searchDataGridView.DataSource as DataTable);
And it would be coded like:
void SearchInfo(DataTable dt){
var dataadapter = blah blah blah;
dataadapater.ClearBeforeFill = false;
dataadapter.Fill(dt);
}

how to sort a datatable except for a one row value

I need to sort a data table and load that data table values to a combo box.Then I need to add a new row called 'All' and it should appear at the top of the combo box items.Here is my work so far,
DataTable dt = bLStatus.GetStatusDetail();
if (dt != null && dt.Rows.Count > 0)
{
dt.DefaultView.Sort= "Description ASC";
cmbCurrentStatus.DataSource = dt;
cmbCurrentStatus.ValueMember = "Description";
cmbCurrentStatus.DisplayMember = "Description";
DataRow row = dt.NewRow();
row["Description"] = "All";
dt.Rows.InsertAt(row, 0);
}
Problem is Row 'All' gets sorted as well,I need to display the row at top How to solve this? Any help will be appreciated.
You could try to insert "All" into the combobox at 0th index. The syntax would be like:
Insert(int insertIndex, object insertItem);
An example would be:
cmbCurrentStatus.Items.Insert(0, (new myClass { Description = ""}));
Reference: https://social.msdn.microsoft.com/Forums/en-US/762a58f5-667d-4e97-a107-86312942f966/can-i-add-items-to-a-combobox-at-a-specific-index?forum=wpf
Similar post in SO: add an item to combobox before bind data from data base
Let me know if it doesn't work.
I answered my question I just needed to copy my Sorted defaultView to another new datatable and add row 'All' to that datatable and bind it to the combo box. Like below,
DataTable dt = bLStatus.GetStatusDetail();
if (dt != null && dt.Rows.Count > 0)
{
dt.DefaultView.Sort = "Description ASC";
DataTable dt2 = dt.DefaultView.ToTable();
DataRow row1 = dt2.NewRow();
row1["Description"] = "All";
dt2.Rows.InsertAt(row1, 0);
cmbCurrentStatus.DataSource = dt2;
cmbCurrentStatus.ValueMember = "Description";
cmbCurrentStatus.DisplayMember = "Description";
}

C# winform Filter combobox items based on datagridview values

I have a combobox called cmbCaseRemain its data populated from datatable by code
cmbCaseRemain.DataSource = ce.GET_ALL_CASEREMAIN();
cmbCaseRemain.DisplayMember = "caseRemain";
cmbCaseRemain.ValueMember = "idCaseRemain";
and I have a datagridview called dgv_CaseRemain gets its data from another datatable
DataTable dt = new DataTable();
dt = ce.GET_ALL_CASEREMAIN_FILTER(Convert.ToInt32(txtidCase.Text));
dgv_CaseRemain.DataSource = dt;
I'm using the combobox to add items to the datagrid view ... and i want after every adding to filter the items in the combobox so the user can't add the same value twice ... so I created a stored procedure with a parameter
CREATE PROC [dbo].[FILTER_CMB_CASEREMAIN]
#ID int
AS
SELECT
[idCaseRemain], [caseRemain]
FROM
[dbo].[tblCaseRemain]
LEFT OUTER JOIN
tblCase_Link_Remain ON idCaseRemain = idCaseRemain_L
WHERE
[idCaseRemain] <> #ID;
and using a code to pass the parameter which filter the combobox when i click on it
DataTable dt = new DataTable();
dt = ce.FILTER_CMB_CASEREMAIN(Convert.ToInt32(this.dgv_CaseRemain.CurrentRow.Cells[1].Value));
if (dt.Rows.Count > 0)
{
cmbCaseRemain.DisplayMember = "caseRemain";
cmbCaseRemain.ValueMember = "idCaseRemain";
cmbCaseRemain.DataSource = dt;
}
but I got an error
Object reference not set to an instance of an object.
Thank you
( sorry for my bad english :-) )
ok. Got it. As I said, it was error on that line. Use below code. Below I add the validation to check the null value.
int n = 0;
DataTable dt;
if (this.dgv_CaseRemain.CurrentRow.Cells[1].Value != null)
{
if (int.TryParse(this.dgv_CaseRemain.CurrentRow.Cells[1].Value.ToString(), out n))
{
dt = ce.FILTER_CMB_CASEREMAIN(n);
}
}
if (dt!=null && dt.Rows.Count > 0)
{
cmbCaseRemain.DisplayMember = "caseRemain";
cmbCaseRemain.ValueMember = "idCaseRemain";
cmbCaseRemain.DataSource = dt;
}

Gridview check if its empty or null

hello I have a code that pulls the data to the gridview using a dataset, what is the best way to check if the Gridview is empty and if it is to not throw an error.. Right now my gridview has the setting to show a message if its empty.. but I just want to null and empty check after attempting to get the data in the dataset
Students students = new Students();
DataSet studentsList = students.GetAllStudents();
GridView1.DataSource = studentsList;
GridView1.DataBind();
If I understand your question correctly, why not just check if the DataSet is empty, before you bind it to the GridView?
If it is, just don't bind it.
DataSet studentsList = students.GetAllStudents();
bool empty = IsEmpty(studentsList); // check DataSet here, see the link above
if(empty)
{
GridView1.Visible = false;
}
else
{
GridView1.DataSource = studentsList;
GridView1.DataBind();
}
You can count the returned row if its has data or not:
DataSet studentsList = students.GetAllStudents();
if(studentList.Tables[0].Rows.Count > 0) //COUNT DATASET RECORDS
{
GridView1.DataSource = studentsList;
GridView1.DataBind();
}
else
{
lblError.Text = "NO RECORDS FOUND!";
}
Regards

How can I export a GridView.DataSource to a datatable or dataset?

How can I export GridView.DataSource to datatable or dataset?
Assuming your DataSource is of type DataTable, you can just do this:
myGridView.DataSource as DataTable
You should convert first DataSource in BindingSource, look example
BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource
DataTable tCxC = (DataTable) bs.DataSource;
With the data of tCxC you can do anything.
Personally I would go with:
DataTable tbl = Gridview1.DataSource as DataTable;
This would allow you to test for null as this results in either DataTable object or null. Casting it as a DataTable using (DataTable)Gridview1.DataSource would cause a crashing error in case the DataSource is actually a DataSet or even some kind of collection.
Supporting Documentation: MSDN Documentation on "as"
Ambu,
I was having the same issue as you, and this is the code I used to figure it out. Although, I don't use the footer row section for my purposes, I did include it in this code.
DataTable dt = new DataTable();
// add the columns to the datatable
if (GridView1.HeaderRow != null)
{
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
dt.Columns.Add(GridView1.HeaderRow.Cells[i].Text);
}
}
// add each of the data rows to the table
foreach (GridViewRow row in GridView1.Rows)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dr[i] = row.Cells[i].Text.Replace(" ","");
}
dt.Rows.Add(dr);
}
// add the footer row to the table
if (GridView1.FooterRow != null)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < GridView1.FooterRow.Cells.Count; i++)
{
dr[i] = GridView1.FooterRow.Cells[i].Text.Replace(" ","");
}
dt.Rows.Add(dr);
}
If you do gridview.bind() at:
if(!IsPostBack)
{
//your gridview bind code here...
}
Then you can use DataTable dt = Gridview1.DataSource as DataTable; in function to retrieve datatable.
But I bind the datatable to gridview when i click button, and recording to Microsoft document:
HTTP is a stateless protocol. This means that a Web server treats each
HTTP request for a page as an independent request. The server retains
no knowledge of variable values that were used during previous
requests.
If you have same condition, then i will recommend you to use Session to persist the value.
Session["oldData"]=Gridview1.DataSource;
After that you can recall the value when the page postback again.
DataTable dt=(DataTable)Session["oldData"];
References:
https://msdn.microsoft.com/en-us/library/ms178581(v=vs.110).aspx#Anchor_0
https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/
I have used below line of code and it works, Try this
DataTable dt = dataSource.Tables[0];
This comes in late but was quite helpful. I am Just posting for future reference
DataTable dt = new DataTable();
Data.DataView dv = default(Data.DataView);
dv = (Data.DataView)ds.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();

Categories

Resources