hi guys I'm trying to save data to database through datagridview with a button but I get the following error every time I run the application and here's my code:
DataTable Table = new DataTable();
BindingSource bindingSource1 = new BindingSource();
string connetionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Database/Database.accdb;";
string sql = "SELECT * FROM IAE;";
OleDbConnection connection = new OleDbConnection(connetionString);
OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connection);
OleDbCommandBuilder cb = new OleDbCommandBuilder(dataadapter);
DataSet ds = new DataSet();
connection.Open();
dataGridView1.DataSource = ds.Tables["IAE"];
dataadapter.Update((DataTable)bindingSource1.DataSource);
connection.Close();
the error : Value Cannot be null. Parameter name: dataTable
need your help and thanks
Reason of error is your bindingSource1.DataSource property is NULL. Your are not assigning any DATASOURCE to your bindingsource class
Related
This is my code:
SqlConnection connection = new SqlConnection(MyConnectionString2);
SqlCommand cmd2;
connection.Open();
try
{
cmd2 = connection.CreateCommand();
cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (#EmailAddress);");
cmd2.Parameters.Add("#EmailAddress", SqlDbType.NVarChar);
cmd2.Parameters["#EmailAddress"].Value = TxbAddEmailUser.Text;
SqlDataAdapter adap = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0];
dataGridView1.DataSource = bs;
}
catch (Exception)
{
throw;
}
TxbAddEmailUser.Clear();
The problem is that my program gives me the error:
System.IndexOutOfRangeException: cannot find tabel 0;
this is my database:
table: tbl_EmailAdress
column: id, int, NOT NULL
column: Email, char(10), NULL
The insert query works, what am I doing wrong?
"Cannot find table 0" indicates that DataSet has empty tables at the first index (0), so that you can't assign data source from it.
The main problem is you're using INSERT command here:
cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (#EmailAddress);");
INSERT command is not intended to return any results for SqlDataAdapter, you need to use ExecuteNonQuery:
cmd2 = connection.CreateCommand();
cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (#EmailAddress)");
cmd2.Parameters.Add("#EmailAddress", SqlDbType.NVarChar);
cmd2.Parameters["#EmailAddress"].Value = TxbAddEmailUser.Text;
cmd2.ExecuteNonQuery();
Note that ExecuteNonQuery only returns affected rows (i.e. 1 row), and you can't assign dataGridView1.DataSource to a single integer value.
If you want to use SqlDataAdapter, you need to use SELECT statement like this example:
cmd2 = connection.CreateCommand();
cmd2.CommandText = ("SELECT * FROM tbl_EmailAdress WHERE Email = #EmailAddress");
cmd2.Parameters.Add("#EmailAddress", SqlDbType.NVarChar);
cmd2.Parameters["#EmailAddress"].Value = TxbAddEmailUser.Text;
SqlDataAdapter adap = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
adap.Fill(ds); // fill the data table from adapter
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0]; // this time the first table is not null or empty
dataGridView1.DataSource = bs;
Similar issue:
Cannot find table 0 error in C#
No need of doing this ,
SqlDataAdapter adap = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0];
dataGridView1.DataSource = bs;
just use
cmd2.ExecuteNonQuery();
I create my TreeView with this piece of code (a method which returns DataSet and it will be equal to TreeView's DataContext):
MySqlConnection con = new MySqlConnection();
con.ConnectionString = ConString;
con.Open();
MySqlDataAdapter femda = new MySqlDataAdapter("SELECT * FROM fem_table", con);
MySqlDataAdapter fileda = new MySqlDataAdapter("SELECT * FROM file_table", con);
DataSet ds = new DataSet();
femda.Fill(ds, "fem_table");
fileda.Fill(ds, "file_table");
DataRelation dr = new DataRelation("DataRelationship",
ds.Tables["fem_table"].Columns["fem_guid"],
ds.Tables["file_table"].Columns["fk_gfem_guid"],true);
dr.Nested = true;
ds.Relations.Add(dr);
return ds;
I use HierarchialDataTemplate to fill the TreeView. In HierarchialDataTemplate, I have CheckBox. I want to reach the data of selected rows. I made some research but they are done with a new class and data from database is added to List of this class. How can I reach the data of selected rows if I use this way to fill the TreeView?
I am trying to display a table data of my db in a DataGridView.here is my code
private void button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("Data Source=SHIRWANIPC;" +
"Initial Catalog=TEST DATABASE;" + "Integrated Security=True");
myConnection.Open();
SqlCommand objcmd = new SqlCommand("SELECT * FROM Customer", myConnection);
SqlDataAdapter adp = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
//adp.Fill(dt);
DataGridView.DataSource = adp.Fill(dt);
}
The code is not giving any error now but but it dosent display the data from my table in my grid ?
You are using class name instead of object (instance) name of DataGridView, check in the html what is ID/name of DataGridView, It is probably Win Forms and you do not have DataBind method there. DataBind method is defined for GridView for ASP.net. Find more about DataGridView here.
DataGridViewObject.DataSource = adp.Fill(dt);
this is the answer to my quetion , hope it helps others who are new to this
SqlConnection myConnection = new SqlConnection("Data Source=SHIRWANIPC;" + "Initial Catalog=TEST DATABASE;" + "Integrated Security=True");
myConnection.Open();
SqlCommand objcmd = new SqlCommand("SELECT * FROM Customer", myConnection);
//objcmd.ExecuteNonQuery();
SqlDataAdapter adp = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
adp.Fill(dt);
//MessageBox.Show(dt.ToString());
dataGridView1.DataSource = dt;
Create an instance of DatagridView:
DataGridView dview = new DataGridView();
....
dview.DataSource = adp.Fill(dt);
dview.DataBind();
You are directly accessing DataGridView properties and tryingto add data to the class. You need to create and an instance of a DataGridView first. Then assign the datable to the object.
Than bind the data to the DataGridView, otherwise the data is not bound to the control and will not be displayed.
DataGridView view = new DataGridView();
dview.DataSource = adp.Fill(dt);
dview.DataBind();
You are not exectuting the query
myConnection.Open();
SqlCommand objcmd = new SqlCommand("SELECT * FROM Customer", myConnection);
DataTable dt = new DataTable(); using
(SqlDataReader sqlDataReader = objcmd.ExecuteReader())
{
dt.Load(sqlDataReader);
sqlDataReader.Close();
}
DataGridView dataGridView1 = new DataGridView();
dataGridView1.DataSource = dt;
I just ran Visual Studio's Code analysis, they told me to use a parameterized query for the following line of code:
using(var DA = new SQLiteDataAdapter(SQL, connectionstring))
The complete method:
public static DataTable SelectAll(string SQL)
{
//create a string(connectionstring), filled with the connectionstring
string connectionstring = "Data Source=" + LogicDatabase.Databasename + ";Version=3;Password=" + Settings.SQLiteDatabasePassword + ";";
//create a new DataSet
DataSet DS = new DataSet();
//Give name to a SQLiteDataAdapter
//Create a new SQLiteDataAdapter and fill it with the sql query, and path of the Database.
using(var DA = new SQLiteDataAdapter(SQL, connectionstring))
{
//Clear the dataset, so we are sure it is empty, before storing items in it.
DS.Clear();
//fill the dataset from the SQLiteDataAdapter.
DA.Fill(DS);
//Fill the DataTable with the first table of the DataSet
DataTable DT = DS.Tables[0];
//return the DataTable
return DT;
}
}
How can I implement parameters in this code?
Use the SQLiteCommand and fill it with your SQL statement. It has a property Parameters which you can fill with instances of SQLiteParameter. After that, you can use this command to create your SQLiteDataAdapter.
I searched some posts but still cant get it work.
I have a window application written in C#, Here I bind the datagridview to my database:
public static DataSet GetDataSet(string sql)
{
using (SqlConnection cn = new SqlConnection(constr))
{
SqlDataAdapter da = new SqlDataAdapter(sql, cn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
and I bind the datagridview in another class:
string sql = "select Amount, Price, Description from myTable";
ds = DbHelper.GetDataSet(sql);
dataGridView2.DataSource = ds.Tables[0];
I created a button for user to update the database after they edit the datagridview:
string sql = "select Amount, Price, Description from myTable";
DbHelper.UpdateDataSet(sql, ds);
MessageBox.Show("done");
public static void UpdateDataSet(string sql, DataSet ds)
{
using (SqlConnection cn = new SqlConnection(constr))
{
SqlDataAdapter da = new SqlDataAdapter(sql, cn);
da.Update(ds);
}
}
Here is the error, occurs at the line da.Update(ds);:
Update requires a valid UpdateCommand when passed DataRow collection with modified rows.
Thanks for help.
EDIT
I can get it work with this:
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
da.UpdateCommand = commandBuilder.GetUpdateCommand();
But only when I show the key in the datagridview as well, otherwise:
Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
How to overcome this if I dont want to show the key in datagridview?
SqlCommandBuilder needs the Primary Key to update the field. You can still load the key to the DataGridView, but hide the column.