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.
Related
I am coding win form app, which checks on startup right of the currently logged user. I had these right saved in MS SQL server in the table. When importing data to Datatable, there is no problem. But when I want to read value, there is message "cannot find column xy".
SqlDataAdapter sdaRights = new SqlDataAdapter("SELECT * FROM rights WHERE [user]='" + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "'", conn);
DataTable dtRights = new DataTable(); //this is creating a virtual table
sdaRights.Fill(dtRights);
Object cellValue = dt.Rows[0][1];
int value = Convert.ToInt32(cellValue);
MessageBox.Show(value.ToString());
I would like, that program would save the value from SQL to int.
You are assuming that you have rows being returned, would be my first guess. You should loop through your DataTable instead of simply trying to access element 0 in it.
DataTable dtRights = new DataTable();
sdaRights.Fill(dtRights);
foreach(DataRow row in dtRights.Rows) {
Object cellValue = row[1];
int value = Convert.ToInt32(cellValue);
MessageBox.Show(value.ToString());
}
using (SqlConnection con = new SqlConnection("your connection string"))
{
using (SqlCommand cmd = new SqlCommand("SELECT [column_you_want] FROM [rights] WHERE [user] = #user"))
{
cmd.Parameters.AddWithValue("#user", System.Security.Principal.WindowsIdentity.GetCurrent().Name);
con.Open();
int right = Convert.ToInt32(cmd.ExecuteScalar());
}
}
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.
im creating wfp application i want to retrieve table to datagridview
with multi value selected in listbox, getting all data that selected from listbox, so the main idea
is apply this query from sql to application
select * from Vwtb where firstname='' or firstaname='' or ..
i have tried with while loop and searched a lot but not worked this is my code please if its something strange for you im not professional :)
string[] orand = { "or"+listBox1.Text };
foreach (string sm in orand)
{
cn.Open();
string select = "select * from productvw where firstname='" + sm + "'";
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable ds = new DataTable();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds;
cn.Close();
}
any type of help will be so appreciated ....
You can convert your array to a string that can be used in IN operator.for achieving that, use this extension method
public static class StaticClass
{
public static string ConvertStringArrayToString(this string[] array)
{
StringBuilder builder = new StringBuilder();
for (int i=0;i<array.Length;i++)
{
builder.Append(array[i]);
if(i+1==array.Length)break;
builder.Append(',');
}
return builder.ToString();
}
}
Then in your code use it like this
string[] orand = { "or"+listBox1.Text };
var values=orand.ConvertStringArrayToString();
cn.Open();
string select =" SELECT * FROM productvw WHERE firstname IN "+"("+values+")"
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable ds = new DataTable();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds;
cn.Close();
You could use the IN operator.
string command = "SELECT * FROM productvw WHERE firstname IN (#names)";
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
dataAdapter.Parameters.Add("#names", names);
The names would be a list of strings, List<string>, and would contain all the first names you want to use.
You can use the following syntax:
SELECT *
FROM productvw
WHERE firstname IN (value1,value2,...);
Start by creating a loop that generates the sql string With the values populated.
Is there a way to map the results of a stored procedure to a generic list instead of a dataset/datatable?
Currently I follow these steps:
Execute stored procedure
Take the result in Dataset
Populate list from the Dataset.
Is there a way to eliminate step (2).
OleDbCommand cm = new OleDbCommand();
cm.Connection = AccessConnection();
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "seltblContacts";
OleDbDataAdapter adp = new OleDbDataAdapter(cm);
DataTable dt = new DataTable();
adp.Fill(dt);
List<tblContacts> LstFile = new List<tblContacts>();
if (dt.Rows.Count > 0)
{
tblContacts t;
foreach (DataRow dr in dt.Rows)
{
t = PopulateContacts(dr);
LstFile.Add(t);
}
}
Yes of course you can do that - just execute your command and get back a reader, and then iterate over the rows in the result set and build up your objects:
using (OleDbCommand cm = new OleDbCommand())
{
cm.Connection = AccessConnection();
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "seltblContacts";
List<tblContacts> LstFile = new List<tblContacts>();
using (OleDbReader reader = cm.ExecuteReader())
{
while(reader.Read())
{
tblContacts contact = new tblContacts();
// here, set the properties based on your columns from the database
contact.FirstName = reader.GetString(0);
contact.LastName = reader.GetString(1);
// etc.
LstFile.Add(contact);
}
reader.Close();
}
return LstFile;
}
For details on OleDbReader and how to use it, see this other SO question or find tons of tutorials and samples online using Bing or Google.
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.