string qry="select *from mom";
Dataset dataset= new Dataset();
SqlDataAdapteradap adap= new SqlDataAdapter(qry,con);
adap.Fill(dataset,"MOM");
DataRow drow = dataset.Tables["MOM"].NewRow();
drow[0] = MRefDDL.SelectedItem.Text;
drow[1] = project.Text.Trim();
drow[2] = agendatopic3.Text.Trim();
drow[3] = presenter3.Text.Trim();
drow[4] = discus.Text.Trim();
drow[5] = conclu.Text.Trim();
drow[6] = "1";
dataset.Tables["MOM"].Rows.Add(drow);
adap = new SqlDataAdapter();
adap.Update(dataset, "MOM");
Here I have One Dataset with MOM Table which fill by data adapter
when after add new row into data set. iwant add this row into database
table with help of adapter.update() Method.But its giving me error:-
Update requires a valid InsertCommand when passed DataRow collection
with new rows.
In the dataadapter, there are insert, update and delete queries that you need to add. The wizard can also do that for you. You can also:
adp.InsertCommand = New SqlCommand(sql, connection)
etc.
Look at https://stackoverflow.com/a/21239695/1662973 for more detailed info.
you are reinitializing the dataadapter just before the Update() method. Please comment this.
//adap = new SqlDataAdapter(); // make this line comment
adap.Update(dataset, "MOM");
Related
I want to arrange the Field Names as user wants to display. I am not using SqlDataSource. I am calling the stored procedure by programming like below.
string cs = ConfigurationManager.ConnectionStrings["HQMatajerConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetTotalSalesQuantity",con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DateFrom", DateFromStr);
cmd.Parameters.AddWithValue("#DateTo", DateToStr);
//cmd.Parameters.AddWithValue("#DateFrom", "2015-01-01 00:00:00");
//cmd.Parameters.AddWithValue("#DateTo", "2015-12-31 23:59:59");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
}
In result, I can see the field name how i have given the Column_name in my query. But, User wants to see the Field Name how they are arranging.
For Example:
select
student_id,student_name ,Class,School_Name
From
Student_Details
If above one is my stored procedure. I will get the Field Name how I mentioned in my query.
But User wants to see the result how they are giving. If user give School_Name,Class,Student_id,School_Name.
Is there anyway to arrange in AspxGridView?
Check my answer Based on my understanding of the question and #mohamed's comment.
Try to use the DataColumn.SetOrdinal method. For example:
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
ds.Tables[0].Columns["School_Name"].SetOrdinal(0);
ds.Tables[0].Columns["Class"].SetOrdinal(1);
ds.Tables[0].Columns["Student_id"].SetOrdinal(2);
ds.Tables[0].Columns["School_Name"].SetOrdinal(3);
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
even if user changes the select statement order of columns will not change.
Use the hiddentext field and get the column names as user wants to display in which order.
string selectedColumns = HiddentxtSelectedColumn.Value;
Move the selectedColumns to array
string[] names = selectedColumns.Split(',');
sda.Fill(ds);
for (int i = 0; i < names.Length; i++)
{
ds.Tables[0].Columns[names[i]].SetOrdinal(i);`
}
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
Now It will run exactly.
I have a little problem with populating my DevExpress Gridview, I want to have a two level gridview and using SqlCommand. At first I created a Dataset and added two tables and also defined relation for them. But it does not work. Can you help me find my problem?
Here is my code
string owner = "SELECT [OBJECTID],[Name] ,[Family] ,[Father] ,[Dftarche] ,[Birthday] ,[education] ,[home_address] ,[farm_address] ,[ensurance] ,[phone] ,[home_number] ,[owner_id] FROM [dbo].[OWNER]";
string property = "SELECT [number] ,[owner_ID] ,[GPSId] ,[Energy],[corp_type] ,[Pool],[irrigation] ,[variety] ,[trees] ,[utilizat] ,[address] ,[water_hour] ,[w_source] ,[w_inche],[w_dore],[NoeMalekiat],[MotevasetBardasht],[Area] ,[OBJECTID],[Shape] FROM [dbo].[Property] ";
string strConnString = Properties.Settings.Default.land_gisConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand command = new SqlCommand(owner, con);
SqlDataAdapter adapter = new SqlDataAdapter();
System.Data.DataSet dsMain = new System.Data.DataSet();
adapter.SelectCommand = command;
adapter.Fill(dsMain, "First Table");
adapter.SelectCommand.CommandText = property;
adapter.Fill(dsMain, "Second Table");
dsMain.Tables.Add(iFeatureSet.DataTable.Copy());
adapter.Dispose();
command.Dispose();
DataRelation newRelation = new DataRelation("املاک شخصی", dsMain.Tables["First Table"].Columns["owner_id"], dsMain.Tables["Second Table"].Columns["owner_ID"]);
dsMain.Relations.Add(newRelation);
GridAttrebuteTable.DataSource = dsMain.Tables[2];
// gridView5.DataSource = dsMain.Tables[1];
dataGridView1.DataSource = dsMain;
I searched and found this http://msdn.microsoft.com/en-us/library/bh8kx08z.aspx and it seems my code is right but it does not show anything in grids
Thank you very much for your help
I Could figure out how to fix it.It works fine now(Above Code is edited) but now If I add a new DataTable I do not know why it does not work again
You need a new GridView for each detail table. You can't display both a master and detail in the same GridView.
Try this example
The following coding doesn't update my table. But rows variable value is 1 after updating.
I cannot understand what is the cause behind this. Please help.
SqlConnection connection1 = new SqlConnection(connectionString);
connection1.Open();
var wktbl = new DataTable();
var cmd = new SqlCommand("SELECT * FROM Test", connection1);
var da1 = new SqlDataAdapter(cmd);
var b = new SqlCommandBuilder(da1);
da1.Fill(wktbl);
wktbl.Rows[0][2] = "5";
da1.UpdateCommand = b.GetUpdateCommand(true);
int rows = da1.Update(wktbl);
Check this page out. It shows the example below of doing an update with the dataadapter.
The following examples demonstrate how to perform updates to modified rows by explicitly setting the UpdateCommand of a DataAdapter and calling its Update method. Notice that the parameter specified in the WHERE clause of the UPDATE statement is set to use the Original value of the SourceColumn. This is important, because the Current value may have been modified and may not match the value in the data source. The Original value is the value that was used to populate the DataTable from the data source.
private static void AdapterUpdate(string connectionString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter dataAdpater = new SqlDataAdapter(
"SELECT CategoryID, CategoryName FROM Categories",
connection);
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = #CategoryName " +
"WHERE CategoryID = #CategoryID", connection);
dataAdpater.UpdateCommand.Parameters.Add(
"#CategoryName", SqlDbType.NVarChar, 15, "CategoryName");
SqlParameter parameter = dataAdpater.UpdateCommand.Parameters.Add(
"#CategoryID", SqlDbType.Int);
parameter.SourceColumn = "CategoryID";
parameter.SourceVersion = DataRowVersion.Original;
DataTable categoryTable = new DataTable();
dataAdpater.Fill(categoryTable);
DataRow categoryRow = categoryTable.Rows[0];
categoryRow["CategoryName"] = "New Beverages";
dataAdpater.Update(categoryTable);
Console.WriteLine("Rows after update.");
foreach (DataRow row in categoryTable.Rows)
{
{
Console.WriteLine("{0}: {1}", row[0], row[1]);
}
}
}
}
I found the problem. It's because connectionString has |DataDirectory|.
The MDF file location is different when running the application.
OleDbConnection _connection = new OleDbConnection();
StringBuilder ConnectionString = new StringBuilder("");
ConnectionString.Append(#"Provider=Microsoft.Jet.OLEDB.4.0;");
ConnectionString.Append(#"Extended Properties=Paradox 5.x;");
ConnectionString.Append(#"Data Source=C:\Clients\Rail\Wheelsets;");
_connection.ConnectionString = ConnectionString.ToString();
_connection.Open();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Vehicles;", _connection);
DataSet dsRetrievedData = new DataSet();
da.Fill(dsRetrievedData);
OleDbCommandBuilder builder = new OleDbCommandBuilder(da);
da.InsertCommand = builder.GetInsertCommand();
////Insert new row
DataRow rowNew = dsRetrievedData.Tables[0].NewRow();
rowNew[dsRetrievedData.Tables[0].Columns[0].ColumnName] = "978";
rowNew[dsRetrievedData.Tables[0].Columns[1].ColumnName] = "222";
rowNew[dsRetrievedData.Tables[0].Columns[4].ColumnName] = "999";
rowNew[dsRetrievedData.Tables[0].Columns[5].ColumnName] = "999";
rowNew[dsRetrievedData.Tables[0].Columns[6].ColumnName] = "999";
dsRetrievedData.Tables[0].Rows.Add(rowNew);
dsRetrievedData.Tables[0].AcceptChanges();
dsRetrievedData.AcceptChanges();
int result = da.Update(dsRetrievedData);
thats the code i use. as you can see i have a paradox table. and some how result = 0 at end of it all.
any ideas what is my mistake?
thanks upfront.
-=Noam=-
What is your InsertCommand?
Also try after removing these line
dsRetrievedData.Tables[0].AcceptChanges();
dsRetrievedData.AcceptChanges();
if you call AcceptChanges all changes in the datatable is accepted so there is no rows which is changed so there is nothing to update
Remove call to AcceptChanges() :
dsRetrievedData.Tables[0].AcceptChanges();
dsRetrievedData.AcceptChanges();
According to MSDN:
Commits all the changes made to this
DataSet since it was loaded or since
the last time AcceptChanges was
called.
Which means, it marks newly added row as not new.
I want to insert a row into the Database using SqlDataAdapter. I've 2 tables (Custormers & Orders) in CustomerOrders database and has more than thousand records. I want to create a GUI (TextBoxes) for adding new customer & orders into the Database to their respective tables.
How should I do it?
I guess the method that is usually followed is
dataAdapter = new SqlDataAdapter (sqlQuery, conn);
dataSet = new DataSet();
da.Fill(dataSet);
Now take the values from textboxes (or use DataBinding) to add a new row into the dataSet and call
da.Update(dataSet);
But the Question is Why should I fetch all other records into dataSet using da.Fill(dataSet ) in the first place? I just want to add a single new record.
For this purpose what I'm doing is, Creating the schema of the Database in the DataSet. like this:
DataSet customerOrders = new DataSet("CustomerOrders");
DataTable customers = customerOrders.Tables.Add("Customers");
DataTable orders = customerOrders.Tables.Add("Orders");
customers.Columns.Add("CustomerID", Type.GetType("System.Int32"));
customers.Columns.Add("FirstName", Type.GetType("System.String"));
customers.Columns.Add("LastName", Type.GetType("System.String"));
customers.Columns.Add("Phone", Type.GetType("System.String"));
customers.Columns.Add("Email", Type.GetType("System.String"));
orders.Columns.Add("CustomerID", Type.GetType("System.Int32"));
orders.Columns.Add("OrderID", Type.GetType("System.Int32"));
orders.Columns.Add("OrderAmount", Type.GetType("System.Double"));
orders.Columns.Add("OrderDate", Type.GetType("System.DateTime"));
customerOrders.Relations.Add("Cust_Order_Rel", customerOrders.Tables["Customers"].Columns["CustomerID"], customerOrders.Tables["Orders"].Columns["CustomerID"]);
I used DataBinding to bind these columns to respective text boxes.
Now I'm confused! What should I do next? How to use Insert command? Because I didn't give any dataAdapter.SelectCommand so dataAdapter.Update() wont work I guess. Please suggest a correct approach.
Set the select command with a "0 = 1" filter and use an SqlCommandBuilder so that the insert command is automatically generated for you.
var sqlQuery = "select * from Customers where 0 = 1";
dataAdapter = new SqlDataAdapter(sqlQuery, conn);
dataSet = new DataSet();
dataAdapter.Fill(dataSet);
var newRow = dataSet.Tables["Customers"].NewRow();
newRow["CustomerID"] = 55;
dataSet.Tables["Customers"].Rows.Add(newRow);
new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataSet);
You can fill the dataSet with an empty set e.g.:
da = new SqlDataAdapter ("SELECT * FROM Customers WHERE id = -1", conn);
dataSet = new DataSet();
da.Fill(dataSet);
Then you add your rows and call update.
For this scenario though it would probably be better not to use SqlDataAdapter. Instead use the SqlCommand object directly for insertion. (Even better, use LINQ to SQL or any other ORM)
SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=test;Integrated Security=True");
SqlDataAdapter da=new SqlDataAdapter("Insert Into Employee values("+textBox1.Text+",'"+textBox2.Text+"','"+textBox3.Text+"',"+textBox4.Text+")",con);
DataSet ds = new DataSet();
da.Fill(ds);
I have to do first time. You can try it . It works well.