I have a datagridview in c# and I am filling it with whatever table from my database I want, getting the table name from a textbox. everything is fine until I try to commit the changes I do in the datagridview to the database.
button2 is the button I will be using for update. I've searched all over and apparently updating the adapter should work, but it doesn't in this case and I can't figure out why. here is my code:
public partial class Form1 : Form
{
static string connstr = "DataSource=localhost;Database=sc2db;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection(connstr);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlDataAdapter adap = new SqlDataAdapter();
DataTable dt = new DataTable();
//BindingSource bs = new BindingSource();
SqlCommand comm = new SqlCommand("select * from " + textBox1.Text, conn);
adap.SelectCommand = comm;
dataGridView1.DataSource = dt;
adap.Fill(dt);
}
catch (Exception ex)
{
label1.Text = ex.Message;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
SqlDataAdapter adap = new SqlDataAdapter();
DataTable dt = new DataTable();
BindingSource bs = new BindingSource();
adap.Update(dt);
}
catch (Exception ex)
{
label1.Text = ex.Message;
}
}
}
Your adap in the button2_Click event handler doesn't have any Command (SelectCommand, DeleteCommand, InsertCommand and UpdateCommand) initialized. So how it can update?
You obviously don't understand how a DataAdapter works. The DataAdapter has 4 Command which are SelectCommand, DeleteCommand, InsertCommand, UpdateCommand. The SelectCommand is required for the method Fill() to work. Other commands are required for the method Update() works, of course in the general case which the DataRows can have all kinds of state: DataRowState.Deleted, DataRowState.Added, DataRowState.Modified. The SelectCommand is also required to build other commands automatically using a CommandBuilder (in SqlClient, that's SqlCommandBuilder). Once you pass a DataTable in the Update() method, all the rows in that table will be browsed through and the state of each DataRow will be checked to see if that row is added, deleted or modified and the adapter will call the corresponding Command (InsertCommand, DeleteCommand and UpdateCommand) it has to perform the actual operation to the database.
In your case, you can try declaring your adap as public and build other commands for it by using SqlCommandBuilder before calling the method Update() like this:
SqlCommandBuilder cb = new SqlCommandBuilder(adap);
Remember that using SqlCommandBuilder() will work only for single table in the Select query, if you have more than 1 table involved you have to build your own Commands for your DataAdapter. That's not difficult, you may want to search more about how to build commands for a DataAdapter.
I hope that helps you get started!
private void button3_Click(object sender, EventArgs e)
{
scb = new SqlCommandBuilder(sqlDataAdapter1);
sqlDataAdapter1.Update(dataSetUser);
}
im able to edit my database from gridview by this code
Related
I have open VFP dbf file from formload got the data into data table and
this also in gridview, I want to use this data result in another button click
How can I call that same data in button click,I am new to this hope this maybe
very easy for some , Please help me.
private void Form1_Load(object sender, EventArgs e)
{
DataTable YourResultSet = new DataTable();
OleDbConnection yourConnectionHandler = new OleDbConnection(
#"Provider=VFPOLEDB.1;Data Source=I:\\Bestall\\T&AData.dbc");
yourConnectionHandler.Open();
if (yourConnectionHandler.State == ConnectionState.Open)
{
string mySQL = "select * from Findat"; // dbf table name
OleDbCommand MyQuery = new OleDbCommand(mySQL, yourConnectionHandler);
OleDbDataAdapter DA = new OleDbDataAdapter(MyQuery);
DA.Fill(YourResultSet);
dataGridView1.DataSource = YourResultSet.DefaultView;
// yourConnectionHandler.Close();
}
}
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;
}
I have this code where I'm trying to update a database from the C# gridview change made in windows application....
The issue occurs in declaring the adapter select command in the update button click event...
I'm not sure which select command or the update command to use such that it updates the datagridview change in the database table....
Could anyone point me in the right direction to solve this issue ?
public partial class KnowledgeBaseForm : Form
{
private SqlDataAdapter SDA = new SqlDataAdapter();
private void button_retrievekb_Click(object sender, EventArgs e)
{
try
{
con.Open();
SqlDataAdapter SDA = new SqlDataAdapter(#"SELECT * From Table1", con);
DT = new DataTable();
SDA.Fill(DT);
bindingsource.DataSource = DT;
dataGridView.DataSource = bindingsource;
if (DT.Rows.Count > 0)
{
dataGridView.Columns[0].DefaultCellStyle.ForeColor = Color.Gray;
dataGridView.Columns[0].ReadOnly = true;
}
else
{
MessageBox.Show("No Knowledge Base Rules Found");
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
finally
{
con.Close();
}
}
}
private void button_update_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you really want to Update these values?", "Confirm Update", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//binding the datasource with the changes made in the gridview
bindingsource.DataSource = dataGridView.DataSource;
SDA.SelectCommand = (//some necessary command or NULL update command which needs to update my database);
scb = new SqlCommandBuilder(SDA);
SDA.Update((DataTable) bindingsource.DataSource);
MessageBox.Show("Updates successfully submitted to CoSD");
}
}
You may want to consider updating the DataSource property of your Grid after any changes were made to the data source associated to it (like bindingSource).
Perhaps something like the following :
SDA.Update((DataTable) bindingsource.DataSource);
// After updating everything, rebind your grid
dataGridView.DataSource = bindingsource.DataSource;
I made a connection to my database, but when I try to view some data from 1 table, is not showing in dataGridView. When I am pressing the button, few seconds seems like is going to show the values, and after that nothing posted in dataGridView
Can anyone explain if I made sth wrong in my code?
I am working in Visual Studio 2013
My code:
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "datasource=localhost;database=microweb;port=3306;username=root;password=pass";
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("select * from reservations", conn);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dta = new DataTable();
sda.Fill(dta);
BindingSource bdsour = new BindingSource();
bdsour.DataSource = dta;
dataGridView1.DataSource = bdsour;
sda.Update(dta);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You should set AutoGenerateColumns to true
bdsour.DataSource = dta;
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = bdsour;
I am making windows application and am stuck at one place.
My problem is that i want to display record in a DataGridView by selecting a ComboBox item but I do not understand the proper way to do it. Please help me in overcome this problem.
private void grid_Load(object sender, EventArgs e)
{
con = new SqlConnection(constr);
try
{
con.Open();
//this.studTableAdapter.Fill(this.pRJTestDBDataSet.stud);
//above line show error for connection to database
da = new SqlDataAdapter("SELECT stud_no FROM stud", con);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "stud_no";
comboBox1.ValueMember = "stud_no";
comboBox1.DataSource = dt;
comboBox1.SelectedIndex = -1;
comboBox1_SelectedIndexChanged(sender, e);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{ con.Close(); }
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.studTableAdapter.Fill(pRJTestDBDataSet.stud);
//above line show error for connection to database
}
i have tried above code but its not working there error like login fail to user
cmd = new SqlCommand("SELECT stud_no FROM stud", con);
da = new SqlDataAdapter(cmd);
da.Fill(dt);
Combobox1.DataSource = dt;
Combobox1.DisplayMember = dt.Columns("Stud_no").ToString;
rebind the DataGrid at each SelectedItemIndex change event of Combo Box by the data you want to bind.
private void button2_Click(object sender, EventArgs e)//button 2 is a show data button
{
if (combo_floor.Text != "")
{
DataSet ds = new DataSet();
string sql = "select floor_id,floor_no,floor_remark,floor_entrydate from Floorinfo where floor_no='"+combo_floor.Text+"'";
ds = c.select_query(sql);
dataGridView1.DataSource = ds.Tables["a"];
combo_floor.Text = "";
}
else
{
showdata();
//showdata()is made for show all data from the given table name
}
}
//connection is in different class so please dont mind