I have a problem, this is my code:
DataTable DT1 = new DataTable();
public static DataTable DATASETRETURN(string queryString)
{
DataSet DS = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter
{
SelectCommand = new SqlCommand(queryString, CLSERVICES.CON)
};
adapter.Fill(DS, "TABLE");
return DS.Tables["TABLE"];
}
private void FE_C_HISTORIQUE_Load(object sender, EventArgs e)
{
E_HISTORIQUE_LV_HISTORIQUE_04.Items.Clear();
string req = "select H.NHistorique, P.Intitulle, H.QuantiteVendu, P.PrixVente,"+
"(P.PrixVente * H.QuantiteVendu) as PQ, H.TypeAction, H.DateAction " +
"from HISTORIQUE as H, PRODUIT as P" +
"where (P.NProduit = H.NProduit)"+
"order by H.NHistorique desc";
DT1 = DATASETRETURN(req);
for (int i = 0; i < DT1.Rows.Count; i++)
{
ListViewItem LV = new ListViewItem(DT2.Rows[i][0].ToString());
LV.SubItems.Add(DT1.Rows[i][1].ToString());
LV.SubItems.Add(DT1.Rows[i][2].ToString());
LV.SubItems.Add(DT1.Rows[i][3].ToString());
LV.SubItems.Add(DT1.Rows[i][4].ToString());
LV.SubItems.Add(DT1.Rows[i][5].ToString());
LV.SubItems.Add(DT1.Rows[i][6].ToString());
E_HISTORIQUE_LV_HISTORIQUE_04.Items.Add(LV);
}
}
After I run the app, I get an error in method DATASETRETURN oin the line
adapter.Fill(DS, "TABLE");
The error is:
System.Data.SqlClient.SqlException
"\"P\" is not a recognized table hints option. If it is intended as a parameter to a table-valued function or to the CHANGETABLE function, ensure that your database compatibility mode is set to 90."
Is there is any solution?
problem caused by the missing spaces between "P_where" and between "H.NProduit)_order"
when specifying multiline queries I prefer:
string req = #"
select H.NHistorique,P.Intitulle,H.QuantiteVendu,P.PrixVente,
(P.PrixVente*H.QuantiteVendu)as PQ,H.TypeAction,H.DateAction
from HISTORIQUE as H, PRODUIT as P
where(P.NProduit = H.NProduit)
order by H.NHistorique desc
";
this way you decrease the chance of missing new lines in your queries.
Related
I use the following code to fill a DataGridView from an Access Database. After a Save button is clicked if the Data Grid is updated, the Database saves the data.
The strange thing is that this works for 2 out of 3 Data Tables. For the last one it throws an exception:
Syntax error in INSERT INTO statement
public Tables(string tabName)
{
InitializeComponent();
this.Text = tabName;
this.query = string.Format("SELECT *" + " FROM [{0}]", tabName);
conn.Open();
detailTable = new DataTable();
string tableName = tabName;
string query = string.Format("SELECT * FROM [{0}]", tableName);
OleDbDataAdapter detailAdapter = new OleDbDataAdapter(query, conn);
if (detailAdapter != null)
{
detailAdapter.Fill(detailTable);
}
DataGridView.DataSource = detailTable;
conn.Close();
}
private void BtnSave_Click(object sender, EventArgs e)
{
OleDbCommand comm = new OleDbCommand(query, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(detailTable);
}
Even if the words are reserved keywords (although I searched them) there is no way of that to be the issue.
More information the tabName can be "Partners", "Salaries", "Descriptions" and "Accounts". It doesn't work only on "Partners".
Okay, turns out I was wrong and I apologize for my stubbornness. The problem was in the e-mail column and I did not see why it had a problem with the dash mark.
I have fetched the data from SQL server to datagridview but I don't know how to change the cell value. I have to change the fetched value 1 and 0 to available and unavailable. here is my code for fetching data ... please help.
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
SqlCommand cmd = new SqlCommand("Select id as 'Book ID',name as 'Name' , status as 'Status' from book where Name = #name", con);
cmd.Parameters.AddWithValue("#name", txtFirstName.Text);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
dataGridView1.DataSource = bsource;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
Please find below answer
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
string sSql=#"Select id as 'Book ID',name as 'Name' ,
Case when status=0 then 'unavailable' else 'available '
End as 'Status' from
book where Name ='"+txtFirstName.Text +"'"
SqlCommand cmd = new SqlCommand(sSql, con);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
First of all, try to store your queries in variables. This will help you in the long run. Also, it is good practise to check whether you are connected or not before trying to send a query away to the server. It is important to remeber that when you fetch data from your server, it will most likely be seen as a string, so if you want to compare it as a number, you need to convert it first.
What you could do is something similar to what i've written below. You count the amount of answers your query returns, then loop through them and check whether they are 0 or 1. Then just replace the value with Avaliable or Unavaliable.
if (dbCon.IsConnect()){
MySqlCommand idCmd = new MySqlCommand("Select * from " + da.DataGridView1.Text, dbCon.Connection);
using (MySqlDataReader reader = idCmd.ExecuteReader()){
// List<string> stringArray = new List<string>(); // you could use this string array to compare them, if you like this approach more.
while (reader.Read()){
var checkStatus= reader["Status"].ToString();
Console.WriteLine("Status: " + checkStatus.Split(' ').Count()); //checks how many items you've got.
foreach (var item in checkStatus.Split(' ').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray()){
var item2 = 0.0; // your 0 or 1 for avaliable or unavaliable..
try{
item2 = double.Parse(item.ToString());
if(strcmp(item2,'0') == 1){ //assuming you only have 0's and 1's.
item2 = "unavaliable";
}else{
item2 = "avaliable";
}
}
catch (Exception){
//do what you want
}
Console.WriteLine("item: " + item2);
}
}
dbCon.Close();
}
}
return //what you want;
}
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.
I can not get any row data from database using c# asp.net.I am trying to fetch one row data from my DB but it is not returning any row.I am using 3-tire architecture for this and i am explaining my code below.
index.aspx.cs:
protected void userLogin_Click(object sender, EventArgs e)
{
if (loginemail.Text.Trim().Length > 0 && loginpass.Text.Trim().Length >= 6)
{
objUserBO.email_id = loginemail.Text.Trim();
objUserBO.password = loginpass.Text.Trim();
DataTable dt= objUserBL.getUserDetails(objUserBO);
Response.Write(dt.Rows.Count);
}
}
userBL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
userDL objUserDL = new userDL();
try
{
DataTable dt = objUserDL.getUserDetails(objUserBO);
return dt;
}
catch (Exception e)
{
throw e;
}
}
userDL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
SqlConnection con = new SqlConnection(CmVar.convar);
try
{
con.Open();
DataTable dt = new DataTable();
string sql = "SELECT * from T_User_Master WHERE User_Email_ID= ' " + objUserBO.email_id + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(dt);
con.Close();
return dt;
}
catch(Exception e)
{
throw e;
}
}
When i am checking the output of Response.Write(dt.Rows.Count);,it is showing 0.So please help me to resolve this issue.
It looks like your your query string has a redundant space between ' and " mark. That might be causing all the trouble as your email gets space in front.
It is by all means better to add parameters to your query with use of SqlConnection.Parameters property.
string sql = "SELECT * from T_User_Master WHERE User_Email_ID=#userID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#userID", SqlDbType.NVarChar);
cmd.Parameters["#userID"].Value = objUserBO.email_id;
I am trying to compare two databases from different dates. I want to load my 'Orders' table from the ending database into a DataTable, then convert that DataTable to a Dictionary<string,int> where string = OrderNumber and int = ClientNumber.
Once I have the Dictionary into memory, I will run my function that goes out to the beginning database and performs a atrOrdersEND.ContainsKey(ordernumber) check. If it is exists nothing will be done, if it does not exist, I want the information of the DataRow to be saved somewhere.
Is this the best way to go about this?
If not, how should I?
static public DataTable getDatabaseInfo(string DB)
{
DB = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB;
OleDbConnection conn = new OleDbConnection(DB);
string query = "SELECT * FROM ORDERS;";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
conn.Open();
try
{
da.Fill(dt);
}
catch (OleDbException ex)
{
}
return dt;
}
static Dictionary<string,int> ToDictionary(DataTable DT)
{ //this doesn't work, I get the 'An item with the same key has already been added' error
var Dict = (from order in DT.AsEnumerable()
select new
{
OrderNumber = order.Field<string>("OrderNumber"),
ClientNumber = order.Field<int>("Client")
}).AsEnumerable()
.ToDictionary(k => k.OrderNumber, v => v.ClientNumber);
return Dict;
}
static public void CheckHistoryBEG(string DB)
{
DB = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB;
OleDbConnection conn = new OleDbConnection(DB);
string query = "SELECT * " +
"FROM Orders";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
string ordernumber = dt.Rows[i]["OrderNumber"].ToString();
if (atrOrdersEND.ContainsKey(ordernumber))
{
atrOrdersEND[ordernumber] = atrOrdersEND[ordernumber] + 1;
}
else
{
atrOrdersEND.Add(ordernumber, 1);
}
}
}
catch (OleDbException ex)
{
}
}
public Main()
{
DataTable EndDB_Data = getDatabaseInfo(endDBLocation);
Dictionary<string, int> atrOrdersBEG = ToDictionary(EndDBData);
CheckHistoryBEG(beginningDBLocation);
}
You can avoid writing any C# code by using linked tables in your MS Access database. From one DB you can reference the table in the other database. Then you can do joins or existence queries between the two databases.