I am trying to copy a row from one table to another in same dataset.
code I am using
dsFrom.Tables["asd2"].Rows.Add(dsFrom.Tables["asd"].Rows[0].ItemArray);
I am getting an NullRefferenceException. I've determined that Rows are null, even though there is data in both tables. Can anyone explain why is this happening? Or maybe there is another solution for my problem.
Thanks
EDIT
This is how I am loading data in them
string query = #"select * from table1;
SqlDataAdapter da = new SqlDataAdapter(query, conn);
DataSet dsFrom = new DataSet();
da.Fill(dsFrom, "asd");
da.Fill(dsFrom, "asd2");
May be you should try to copy rows by this way:
foreach (var row in dsFrom.Tables["asd"].Rows)
{
dsFrom.Tables["asd2"].ImportRow(row);
}
Related
Below is my code to get data from my oracle database to display a table with multiple rows in asp.net(C#). Te columns will be Name, Section and Gender. The headers of the table are hardcoded, only rows' data should be populated from database. On executing the code, I am getting only 1st row coming from database. Remaining rows are not coming. Please suggest for the solution.
public void GetDailyData()
{
using (OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["dataconn"].ToString()))
{
try
{
string query = #"SELECT name,section, gender FROM t_student WHERE order by TRUNC(admissionDate)";
OracleCommand cmd = new OracleCommand(query, conn);
conn.Open();
OracleDataAdapter da = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
cmd.ExecuteNonQuery();
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (ds.Tables[0].Rows.Count > 0)
{
LabelName.Text = ds.Tables[0].Rows[0].Field<string>(0);
LabelSection.Text = ds.Tables[0].Rows[0].Field<string>(1) ;
LabelGender.Text = ds.Tables[0].Rows[0].Field<string>(2) ;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}
You're only seeing row data from the first row because that's what you're pulling out when you say ds.Tables[0].Rows[0] - Rows[0] will always be the first row of the table
This entire block of code is confused;
you cannot show multiple rows using single labels - Use a Grid component and DataBind it to the datatable.
The code uses a loop to go through table rows but checks if the table has rows, inside the loop ( the loop won't run if it doesn't) and instead of using the enumerated row it always access the first row on every pass of the loop.
Do not use a DataSet, just make a new DataTable and fill it - datasets are for when you want to work with multiple related datatables and in this case of a single table are a useless extra layer.
Do not ExecuteNonQuery on the command, it's a useless operation - the dataadapter will execute the query during the fill, you don't need to do it (and ExecuteNonQuery is for insert/update/delete/create etc - this is a select).
Your code could/should look more like:
DataTable dt = new DataTable();
da.Fill(dt);
gridControl.DataSource = dt;
gridControl.DataBind();
That's it. All the rest of the code (apart from the command and connection) should be thrown away
I've found some solutions on stackoverflow and other sites like this (assume the connection is already opened):
sc.Open();
DataSet ds = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter("select * from mydatabase.mytable;", sc);
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(ds);
dataGridView1.DataSource = ds;
sc.Close();
but it's not working propoerly. All I get is an empty datagridview which let's me assume that the data is not loaded.
When I first loaded the data to a list - list myList with MySQLDataReader, I could load the data normally to the datagridview with the following code:
foreach (myClass a in myList)
{
this.dataGridView1.Rows.Add(a.Id, a.2ndColumn, a.3rdCoulmn, and so on..;
}
Can you please tell me why I couldn't load the datatable with the MySQLAdapter? Some of the asnwers I checked showed I should be able to load it and display it this way..
You should take a look at this link, I've used it a while ago and it worked fine for me.
Also, the for loop you have isn't needed, when linking an collection to the DataSource property it should automatically update the GridView.
I'm trying to search for a code entered by the user in a sqlite table if it's found add the row to a dataGridView. the problem is that the code I'm using clears the datagrid every time I add a new row.
Here is the code I'm using
DataTable dt = new DataTable();
String insSQL = "select * from Produtos where codigo =" + txtCodigo.Text;
String strConn = #"Data Source=C:\caixa.sqlite";
SQLiteConnection conn = new SQLiteConnection(strConn);
SQLiteDataAdapter da = new SQLiteDataAdapter(insSQL, strConn);
da.Fill(dt);
dataGridViewProdutos.DataSource = dt.DefaultView;
I tried to change the dataGridViewProdutos.datasource to dataGridViewProdutos.Rows.add(dt); them it adds a row but always empty.
I fixed it removing the DataTable dt = new DataTable(); from the loop. I also changed the dt.DefeulView to only dt as sugested by N4TKD and Im seeing no diference so Im using it.
Also thanks for the links it was very helpfull since I was struggling to make my colums fill the dataGridView space.
i'm trying to add a new row to my datatable.
I've no error while running this code but nothing happened in my table.
Here's my code :
string table = "`DONNEE ENTRANT`";
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * From " + table, _conn);
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(adapter);
DataTable dataTable = new DataTable(table);
adapter.Fill(dataTable);
DataRow row = dataTable.NewRow();
row["CODE LIAISON"] = "TEST";
dataTable.Rows.Add(row);
dataTable.AcceptChanges();
adapter.Update(dataTable);
Any idea what i'm doing wrong (in this way, I know that we can run command with oleDb but really don't like this way ...).
Thanks
Based on what you're doing it appears you want that new row to end up in the database. So remove this line:
dataTable.AcceptChanges();
because that's changing the RowState to Unchanged and you need it left at Added. Further, you need to make sure that your adapter has an InsertStatement defined so it can use it.
I would use [] instead of `` but I believe the answer to correct your problem was already given by #Michael Perrenoud
I've got an assignment which requires me to update the northwind database,
I've done everything like the tutorials say as follows
I fill The DataTable Using The DataAdapter.Fill(table).
I build the Delete,Insert,Update Commands using CommangBuilder
SqlDataAdapter adapter = new SqlDataAdapter(selectStr, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.DeleteCommand = builder.GetDeleteCommand(true);
adapter.UpdateCommand = builder.GetUpdateCommand(true);
adapter.InsertCommand = builder.GetInsertCommand(true);
adapter.Fill(employees_table);
I also set a primary key for the table:
DataColumn[] employees_keys = new DataColumn[2];
employees_keys[0] = employees.Columns["EmployeeID"];
employees_table.PrimaryKey = employees_keys;
Now I've attempted to delete and add a row:
// accepts an employee object and creates a new new row with the appropriate values for
// an employee table row
DataRow row = ConvertEmployeeToRow(employeeToAdd);
employee_table.Rows.Add(row);`
and deleting a row:
DataRow row = employees.Rows.Find(employeeToDismiss.ID);
employees.Rows.Remove(row);
I should also point out that I've attempted to use row.SetAdded() and row.Delete()
Anyway, at the end when I try to update the database
int k = employees_adapter.Update(employees_table);
on added rows sometimes k get valued, on remove never, and in either case nothing really gets updated at all in the database itself.
Any insight of what I'm doing wrong?
Make sure you're calling employee_table.AcceptChanges() after the call to Update() to save the changes to the database.
Check if the CommandBuilder really makes an Update command for you, like this:
MessageBox.Show(adapter.UpdateCommand.CommandText);
If the primary key info is missing it won't build the update command at all!
I am little confuse here your SqlDataAdapter name is adapter and you are doing updation in employees_adapter.The steps are so simple to work with SqlDataAdapter just follow theses
Step No 1:
SqlDataAdapter adapter = new SqlDataAdapter(selectStr, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataTable employees_table= new DataTable ();
adapter.Fill(employees_table);
Step No 2:
After you got the data in dataset start manipulation on it..
To insert :
DataRow MyRow = employees_table.NewRow();
//Now Fill data in MyRow
employees_table.Tables[0].Rows.Add(MyRow);
employees_table.AcceptChanges();
adapter.Update(employees_table);
To Delete :
/get only the rows you want
DataRow[] result = employees_table.Select("ID ="+id); //id will be provided by you
//Now do here data updation
employees_table.AcceptChanges()
adapter.Update(employees_table);
Like wise you can apply updation..But after doing any changes must call
table.AcceptChanges() and then'adapter.Update(employees_table)'