Adding Data in the datagridview - c#

I have a little problem here, and I admit im not so very good at this but you guyz can help me, right?
so here my problem.
I created this codes:
private void button1_Click(object sender, EventArgs e)
{
connect = new OleDbConnection(coo);
connect.Open();
command.Connection = connect;
DataTable dt = new DataTable();
OleDbDataAdapter ODA = new OleDbDataAdapter("SELECT * FROM Items where itemno = '" + textBox1.Text + "'", connect);
ODA.Fill(dt);
dataGridView1.DataSource = dt;
}
which if I click my button "Enter" it can add or can insert data in the datagridview but if I click the "Enter" button again with another data, the previous data I,ve just entered was disappered and replace it with another one and all i want is add an another data by not replacing or deleting the other data i,ve just entered.
What should I do?

Using DataTable.Merge will append each successive DataTable to the previous one that was assigned to the DataGridView, as long as the schema (i.e. column types) is the same.
Replace this:
dataGridView1.DataSource = dt;
With this:
if (dataGridView1.DataSource == null)
dataGridView1.DataSource = dt;
else
((DataTable)dataGridView1.DataSource).Merge(dt);

I think you just need to do a databind.
Try adding dataGridView1.DataBind() to the end of your code.

Related

GridView not appearing on webpage

I am building a web form. I have one search field and a search button. I am connecting to MS Access database to retrieve and display the result on the grid view. But my grid view is not appearing on the web page.
Can anyone please help me to find out where I am wrong?
Here is my aspx.cs code:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Smita\\Desktop\\Project.accdb");
DataTable dt = new DataTable() ;
if (txtMerchant.Text.Length > 0)
{
con.Open();
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand("select * from Test where Merchant ID like '" + txtMerchant.Text + "%'", con);
DBAdapter.Fill(dt);
GridView1.DataSource = dt;
}
You have to call the DataBind, binding method first after you assign the data source.
Like that:
GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.DataSource = dt; //Assigned a blank table.
"dt" Doesn't seem to point to anything.

Refreshing multiple datagridviews with single button click

Not sure if this question has been asked before, so here goes..
I have a front end app coded in C# windows forms. On a second form i have two datagridviews that gets populated from two different sql server pre-defined views
I need to refresh both datagrids at the same time with a single button click
My button click even looks like this..
private void RefreshBTN_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("removed for illustration only");
string query = "select * from daily_orders order by orderno DESC";
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
How i understand this is, C# opens new connection, queries the DB and returns by filling datagridview1 with the required data. I would like the same click event to request data from another sql view and populate another datagridview at the same time. Visually both grids are aligned vertically on the same form, one on to of the other.
Many thanks in advance
Move the code for refreshing Grid1 into a separate function. Then copy paste and duplicate that function for Grid2. Change the SQL for Grid2 as well as the Grid2 name. Rename the copied function with 2. Then add a call to both functions so your button click will refresh both grids.
private void RefreshBTN_Click(object sender, EventArgs e)
{
//call both functions to refresh both on button click
RefreshGrid1();
RefreshGrid2();
}
private void RefreshGrid1()
{
SqlConnection myConnection = new SqlConnection("removed for illustration only");
string query = "select * from daily_orders order by orderno DESC";
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
//give this function a unique name to represent the second grid refresh
private void RefreshGrid2()
{
SqlConnection myConnection = new SqlConnection("removed for illustration only");
string query = "select * from daily_orders order by orderno DESC";
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
//rename this to your second grid name
dataGridView2.DataSource = dt;
}

Exporting log file when datagridview has been updated

I have a datagridview in C# that is used to read data from a SQL database. I have it setup so when there is missing criteria, the user can update the datagrid which then updates my SQL database. However I'm wanting / needing to have a log file generated and exported with what column or field that was changed in the datagrid out to the local machine. Have some idea of maybe adding an event handler on the datagrid and when cellvaluechanged = true; run export? Any help is appreciated, thx!
(No code to provide, not sure how to approach this type of method (still kinda green to C#)).
sqldataAdapter da;
sqlCommandBuilder scb;
DataTable dt;
SQLConnection con = (my connection);
private void btnEnter_Click(object sender, EventArgs e)
{
try
{
//Searches database for what is plugged into txtbox.
da = new SqlDataAdapter("SELECT * FROM [sqltable] WHERE [columnA]='" + txtData.Text + "' OR [ColumnB]='" + txtData.Text + "' OR [ColumnC]='" + txtData.Text + "' OR [ColumnD]='" + txtData.Text + "'", con);
ds = new DataSet();
dt = new DataTable();
ds.Clear();
da.Fill(dt);
dg.DataSource = dt;
con.Open();
con.Close();
private void btnUpdate_Click(object sender, EventArgs e)
{
//when button is clicked, the SQL Database gets updated with the data that is plugged into the datagridview.
scb = new SqlCommandBuilder(da);
da.Update(dt);
You can grab the DataTable of before the change was made, and the dataTable after the new changes have been made, then do this.
A.Merge(B); // this will add to A any records that are in B but not A
return A.GetChanges(); // returns records originally only in B
Then go through and write the values to a log that a A.Getchanges() returns. Those would be the changes made.
I got it:
dg.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText;
dg.SelectAll();
Clipboard.SetDataObject(dg.GetClipboardContent());
File.WriteAllText(#"path.txt", Clipboard.GetText(TextDataFormat.Text));

How to edit dynamically generated datatable and datagridview?

So i have a form that looks like this:
Image Link
and I generate the datatable for the dataviewgrid in the load function:
private void loadEmpresas(){
MySqlConnection myConn = new MySqlConnection(gVariables.myConnection);
MySqlCommand command = new MySqlCommand("Select codempresa as 'Codigo', nomempresa as 'Nombre empresa' from contabilidad.empresas", myConn);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = command;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
the table in mysql looks like this:
SQL Table Image Link
so when it is running it shows this:
Now the problems that i have are that i have no idea how to modify the width of the columns, id like the entire table to cover that gray space and i want that on click it selects the entire row not just a cell. When it clicks the row i want to pupulate the rest of the textboxes but i have a problem with the click event which for testing purposes is this:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("clicked");
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
MessageBox.Show(row.Cells[0].Value.ToString() + row.Cells[1].Value.ToString());
}
else
{
MessageBox.Show("wat");
}
}
when I click it doesn't even show a messagebox sometimes, I seriously have no idea how to handle the click row event properly :C help please T_T
For updating the column widths try using DataGridViewColumn.width:
DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 60;
DataGridViewColumn.Width property information.
To select the entire row you need to change the SelectionMode of the DataGrid to FullRowSelect:
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.MultiSelect = false;
SelectionMode information.

How to select data from table selected in dropdownlist?

I have a dropdownlist on a page and in a dropdownlist I have names of the tables in database.
I don't know how to insert data from the selected table in the gridview or datalist.
I tried with using the code from another c# project I did in school, but it didn't work
edit: answer added here
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(connectionString);
OleDbDataAdapter da = new OleDbDataAdapter (string.Format("SELECT * from {0}", dropDownList.SelectedValue), con);
DataSet ds = new DataSet();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
con.Close();
}
You can tell the code to put the dropdowlists selected item's value in the query as follows:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con= new OleDbConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(string.Format("SELECT * FROM {0}",DropDownList1.SelectedValue), con);
DataSet ds = new DataSet();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
con.Close();
}
I've tested this before posting it and it works on my machine. When you so if you can not get it worked the problem should be somewhere else.
That is very easy to do. I assume your dropdownlist is in your gridview which is also a asp gridview. If this is the case then in the event you have catching the selectedindexchange or by button click. You will have to find the dropdown in the gridview and then use the selectedvalue property. It will look like this to find it(place this in your event handler)
Dim ddl as dropdownlist = gridview.row(e.rowindex).findcontrol("dropdownID")
Dim val = ddl.selectedvalue
The only changes that might have to be made in regards to finding the control is depending on what rowtype the dropdown is in and also the event being used. If the above wont find the control you can try gridview.row.findcontrol("dropdownID")
Once you get the value, you can call the method for the insert and pass it as a parameter :)

Categories