Delete All row from DataTable in DataSet - c#

I'd like to erase all row in a datatable located in a dataset and then update the DataBase using the method Update() of TableAdapter.
The insert works fine, I put it so you can see what I'm doing. I tried the method Clear() for datatable which was supposed to erase all row but at the moment it does nothing.
I would like to use a kind of SQL query like DELETE * FROM demande; but I dont get how to do it
protected void InsertDemande_Click(object sender, EventArgs e)
{
//TB = textBox
//Parsing date (5th row of my dataTable is type date)
string[] tabdate = TB_date_demande.Text.Split('/');
DateTime date = new DateTime(int.Parse(tabdate[2]), int.Parse(tabdate[1]), int.Parse(tabdate[0]));
//In my dataset "Demande", on my table "Demande", i add a new row type "demande" with all good parameters
ds_Demande.Demande.AddDemandeRow(TB_demande_ID.Text, TB_user_ID.Text, TB_nom_fichier.Text, int.Parse(TB_poids_fichier.Text), date);
ta_Demande.Update(ds_Demande);//update the database
LabelResponse.Text = "Ajout effectué avec succès";
GridViewDemande.DataBind();//refresh gridview
}
protected void ClearTable_Click(object sender, EventArgs e)
{
ds_Demande.Demande.Clear();//doesn't seem to do anything
ta_Demande.Update(ds_Demande);
GridViewDemande.DataBind();
}

// Clear all rows of each table.
ds_Demande.Clear();
// alternatively:
foreach(var row in ds_Demande.Rows) {
row.Delete();
}

for(int i = 0; i<ds_Demande.Count; i++)
{
ds_Demande.Rows[i].Delete();
}

Related

How do I access a table name from data grid view?

So I'm trying to cope with an app project in c#/mssql.
It is Windows Froms app.
I'm connected to db, I can show all the tables in my db in the form onload, but i don't know how, or if I can do sth like: when these table names shows click on any and it will send the db name as a variable to function, which will show me the content of the folowing table. I've learned about cellclick event, but i still don't know how do i make it work.
So the code below works perfectly fine
DbClassShow showObj = new DbClassShow();
private void MyWindow_Load(object sender, EventArgs e)
{
DataTable dt = showObj.Select();
QueryView.DataSource = dt;
}
but I want it to show the content of the table, when i click on it, but I can't attach like clik event to table name, because when the app is not running i can't even see content of the data grid view.
What do I do in this situation?
Sorry guys for bothering, I've been trying this and had no clue, but finally I resolved it on my own! Here's what i did:
dbClassTables showTab = new dbClassTables();
private void QueryView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
int indexOfRow = e.RowIndex;
DataGridViewRow selectedRow = QueryView.Rows[indexOfRow];
DataTable dt1 = showTab.Select(selectedRow.Cells[2].Value.ToString());
QueryView.DataSource = dt1;
}
Created a new class with select method with parameter and it works, I'm gonna make it more valid using abstract class or interface i think, but yeah, that's it.
public DataTable Select(string tbl_name)
{
...
string sql = "SELECT * FROM {0}";
string data = tbl_name;
sql= string.Format(sql, data);

C# How do I copy from one data grid to another without overwriting my previous selection?

I have 2 datagrid views with one datatable. I am trying to have a button that when clicked it adds the rows from csv_datagridview to optimal_datagridview. The below works however whenever I deselect an entry in csv_datagridview and hit the button again it clears that selection. I would like to have the selection stick each time.
if (selectedRowCount <= 9)
{
List<object> destList = new List<object>();
foreach (DataGridViewRow row in csv_datagridview.SelectedRows)
destList.Add(row.DataBoundItem);
optimaldataGridView.DataSource = destList;
Thank you so much in advance :)
It is unclear what your exact problem is with the little code you show, but from your statement whenever I deselect an entry in csv_datagridview and hit the button again it clears that selection. I am guessing that if nothing is selected, the data in optimaldataGridView clears when you press the add selected button.
I will assume the csv_datagridview is bound to a table. Your posted code shows the creation of new List destList which you fill with the selected rows from the csv_datagridview. Then you set optimaldataGridView data source to the destList. One issue I see in this picture is that as soon as you leave the if (selectedRowCount <= 9) clause… destList will no longer exist. As a data source for a DataGridView on your form, I would think you would want to keep this List global as long as the form is open. Either way... you are not adding the selected rows, you are simply removing the existing rows and then adding what was selected in csv_datagridview.
I hope the code below will help. I created two DataTables, one for each DataGridView. The csv_datagridview data table is filled with some data, the second data table is left empty. Then simply add the selected rows from the csv_datagridview to the optimaldataGridView’s DataTable… Then refresh optimaldataGridView.
DataTable table1;
DataTable table2;
public Form1() {
InitializeComponent();
csv_datagridview.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
optimaldataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
table1 = GetTable("table1");
table2 = GetTable("table2");
FillTable(table1);
csv_datagridview.DataSource = table1;
optimaldataGridView.DataSource = table2;
}
private void button1_Click(object sender, EventArgs e) {
if (csv_datagridview.SelectedRows.Count > 0) {
foreach (DataGridViewRow row in csv_datagridview.SelectedRows) {
DataRowView dr = (DataRowView)row.DataBoundItem;
table2.Rows.Add(dr.Row.ItemArray[0], dr.Row.ItemArray[1], dr.Row.ItemArray[2]);
}
optimaldataGridView.Refresh();
}
}
private DataTable GetTable(string name) {
DataTable table = new DataTable(name);
table.Columns.Add("col1");
table.Columns.Add("col2");
table.Columns.Add("col3");
return table;
}
private void FillTable(DataTable table) {
for (int i = 0; i < 10; i++) {
table.Rows.Add("R" + i + "C0", "R" + i + "C1", "R" + i + "C2");
}
}
Hope this helps.
Your code is working on my side.
Created a DataTable for Datasource of csv_datagridview.
Selected some rows in this grid.
Clicked the button to copy the selected rows to the
optimaldataGridView
The selected rows are still selected.
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.ReadXml(Application.StartupPath + #"\test.xml");
csv_datagridview.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
csv_datagridview.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e)
{
List<object> destList = new List<object>();
foreach (DataGridViewRow row in csv_datagridview.SelectedRows)
destList.Add(row.DataBoundItem);
optimaldataGridView.DataSource = destList;
}
Make sure you have no events attached to the grids that may affect the selection.

access database not updating after editing fields

I am developing a program for a Computer Store using c# with VS2010 and Database Provider = OleDB.
I need a form for updating the existing Products information in the stock. So I have a DataGridView to show the products Table (Edit property = on)
My code for updating a row :
private void button1_Click(object sender, EventArgs e)
{
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewRow UpdateRow = dataGridView1.Rows[i];
if (UpdateRow.Selected == true)
{
try
{
com.CommandText = "UPDATE Products SET ProductName=#pname,Model=#model WHERE ProductID= " + UpdateRow.Cells[0].Value + "";
com.Connection = con;
com.Parameters.AddWithValue("#pname", UpdateRow.Cells[1].Value);
com.Parameters.AddWithValue("#model", UpdateRow.Cells[2].Value);
int count = com.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
con.Close();
}
That code works and it updates the access database file but it's only for one row (the selected row)
Now i want to update every edit the user have done in the DataGridView
So all i have to do is to delete the line if (UpdateRow.Selected == true) and that way , the loop will go for every row and update the info .
I debugged the program and it didn't crash but the Access database didn't update anything! I wonder why...
There are 2 methods to accomplish this:
Follow the dataset and datatable route, assign the datatable to the grid and then use the getchanges() method to retrieve the rows which have changed and then update the selected rows into the database
Use the following following function to capture the rowindex property of the changed row
private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// use e.rowindex to get the row being modified and keep that in some list and
//after update button is pressed get the rows and update accordingly
//
}

Putting image in DataTable and setting table as datasource to gridview

I'm having problems with putting an image in a DataTable and setting this table as datasource to gridview, I've searched everywhere, but no I had no luck.
Here is the problem:
private void populateGrid()
{
// Gets a datatable from a stored procedure
DataTable ragTable = ProjetoBO.HistoricoRAGStatusProjeto(Convert.ToInt32(Session["idProjeto"]));
int group= -1;
int cont = 1;
var table = GetDataTable(ragTable);
DataRow dataRow = table.NewRow();
foreach (DataRow row in ragTable.Rows)
{
cont++;
if (Convert.ToInt32(row[9]) != group)
{
cont = 1;
group= Convert.ToInt32(row[9]);
table.Rows.Add(dataRow);
dataRow = tabelaFinal.NewRow();
}
dataRow[0] = DateTime.Parse(row[2].ToString()).ToShortDateString();
//putting some random image just for testing purpose
dataRow[cont] = Properties.Resources.myIcon;
}
//my grid
histRagStatus.DataSource = table ;
histRagStatus.DataBind();
}
//Creates a dataTable with the columns I need
private DataTable GetDataTable(DataTable ragTable)
{
var newTable= new DataTable();
newTable.Columns.Add("Date");
foreach (DataRow row in ragTable.Rows)
{
if (!newTable.Columns.Cast<DataColumn>().Any(column => column.ColumnName.Equals(row[6].ToString())))
{
var newColumn= new DataColumn(row[6].ToString());
newTable.Columns.Add(newColumn);
}
}
return newTable;
}
I've been trying everything I can, creating a new column like var newColumn= new DataColumn(row[6].ToString(),typeof(Bitmap)); / converting to an image and putting there / changing the datatype of the column before adding to the DataTable... But no luck... I just need the right way to get an image from Properties.Resources and putting it on a DataTable, that will bind to a grid and the image will appear on the gridview...
Any help is precious to me right now =D
I'm not aware of a method for natively rendering image files (including BMP) in a GridView.
In your case, what I'd do is save that bitmap in a local file in the virtual directory. Once you have the file name, you can bind that filename to an ImageField column in the GridView.
Storing the binary Bitmap in the DataTable only works in Windows Forms with the DataGridView Control. In ASP.NET DataGrid you must reference to a image URL. The simple way is enable in your DataGrid the Event RowDataBound.
Then wire up with code to your image location.
protected void GridView1_RowDataBound(object sender, GridViewRowWEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//Setup in your image column index. By Example setting 0
e.Row.Cells[0].Text=Server.HtmlDecode(#"<img src=""./Images/pdf.gif"" />");
}
}

add row to a dynamic datagridview

i have a windows form where i am trying to add the path of a file usnig folderbrowserDialog
i have this code on at form load
public FileMgmt()
{
InitializeComponent();
//
// Here we create a DataTable with four columns.
//
DataTable table = new DataTable();
table.Columns.Add("Check", typeof(bool));
table.Columns.Add("Path", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
table.Rows.Add(false, "", DateTime.Now);
dataGridView2.DataSource = table;
}
this is the code when i click a button to search for folders and add the path to the above gridview which already has the above row
private void AddPubPath_Button_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
dataGridView2.Rows.Add(false, folderBrowserDialog1.SelectedPath, DateTime.Now);
}
but i get the following error..
Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.
please, any suggestions
Since your DataGridView is bound to a DataTable, you'll need to update your DGV through your DT. That's what the error is telling you.
Update your button click code to the following:
private void button1_Click(object sender, EventArgs e) {
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
var table = (DataTable)dataGridView2.DataSource;
var newRow = table.NewRow();
newRow["Check"] = false;
newRow["Path"] = folderBrowserDialog1.SelectedPath;
newRow["Date"] = DateTime.Now;
table.Rows.Add(newRow);
}
}
This code gets the DataTable your DGV is bound to, creates an empty new row for the table, populates this new row with data and then finally adds the row to the DataTable.
I've also added code that makes sure the user actually selected a folder with your FolderBrowserDialog before attempting to add the row.
Edit in response to your question about making only the Check column editable
// Make all the columns you don't want editable read only.
table.Columns["Path"].ReadOnly = true;
table.Columns["Date"].ReadOnly = true;

Categories

Resources