Filling Customer Generated dataTable with the results from a user query - c#

So i used datasource wizard in VS2012 to generate DataSet from my Database.
So now i am trying to fill in autogenerated datatable for each table in the database to be filled with data. However i am running into some problems.
string var = comboBox1.Text;
SqlDataAdapter ad = new SqlDataAdapter(#"SELECT * FROM Contacts WHERE "+var+" LIKE "+textBox1.Text+";",connection);
DataTable dataTable = new DataTable();
ad.Fill(dataTable);
ERPDataSet.ContactsDataTable dt = new ERPDataSet.ContactsDataTable(dataTable);
contactsTableAdapter.Fill(dt);
So now the problem here is That when i pass Datatables into the constructor of ContactsDataTable i get the exception null reference exception "Object reference not set to an instance of an object."
However i know for a fact that datatable is not empty.
So any help here would be appreciated.

Short answer: debug it.
Long answer: inspect the actual command text, and then compare that to what you assume by executing it with the same credentials/authority. It is a certainty that you have an incorrect assumption.
My guess without having either the values of the table or the var variable in hand, is that your LIKE clause is functionally equivalent to an equality comparison because you are missing wildcard characters in your command text that you are assuming are present at execution or even that you are missing vital string literal single quotes.
Perhaps this would work as you expect:
SqlDataAdapter ad = new SqlDataAdapter(String.Format(#"SELECT * FROM Contacts WHERE {0} LIKE '%{1}%', var, textBox1.Text), connection);

Ok so i was able to solve my problem by directly executing the query against the tableadapter instead of using separate data adapter
string var = comboBox1.Text;
contactsTableAdapter.Adapter.SelectCommand = new SqlCommand(#"SELECT * FROM Contacts WHERE " + var + " LIKE " + textBox1.Text + ";");
contactsTableAdapter.Adapter.SelectCommand.Connection = connection;
contactsTableAdapter.Adapter.Fill(eRPDataSet.Contacts);

Related

No value given for one or more required parameters in Oledb query

I'm trying to query a CSV file. It works when I do a simple select, but as soon as I try to add a where clause, I run into No value given for one or more required parameters.
Obviously, it sounds like it's not getting the supplied parameter, but I've tried to pass it in a number of ways. See below for some code samples
DateTime lastRunDate = Convert.ToDateTime(ConfigurationManager.AppSettings["LastRunDate"]);
OleDbConnection conn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + base.applicationRoot + ";" +
"Extended Properties=\"text;HDR=Yes;FMT=CSVDelimited\"");
// This works just fine
//OleDbDataAdapter adapter = new OleDbDataAdapter(String.Format("select * from {0}",
// This gives the error
OleDbDataAdapter adapter = new OleDbDataAdapter(String.Format("select top 100 * from [{0}] where {0}.sale_date = #sDate", base.csvFileName), conn);
//adapter.SelectCommand.Parameters.Add("#sDate", OleDbType.DBDate).Value = lastRunDate;
adapter.SelectCommand.Parameters.AddWithValue("#sDate", lastRunDate);
// This also gives the same error as above
//OleDbDataAdapter adapter = new OleDbDataAdapter(String.Format("select top 100 * from {0} where sale_date = '{1}'", base.csvFileName, lastRunDate), conn);
base.csvFileName, lastRunDate.ToShortDateString()), conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
I don't know anything about C#, and I'm still decently new to SQL, but perhaps it's the SELECT TOP part of your query. I know that SELECT TOP isn't really accepted on all db systems, and that it's included in both of your queries that are giving you problems. Have you tried removing that and using LIMIT instead?
"select top 100 * from [{0}] where {0}.sale_date = #sDate"
to
"select * from [{0}] where {0}.sale_date = #sDate LIMIT 100"
I would have added this as a comment as it's not a concrete answer, but I have not the required rep yet.:(
Remove this line. You have added parameter twice.
adapter.SelectCommand.Parameters.AddWithValue("#sDate", lastRunDate);
and make sure the value is present in lastRunDate variable. it should not be null.
EDITED:
Remove table name from the where condtion, Use like this
select top 100 * from [{0}] where sale_date=#sDate
Column Names in the Excel file and in the Query are not Same.
Either column name is missing.
Column Name not existing in the Excel File.
I found he issue with this. The query simply didn't understand the column names.
I thought that setting HDR=Yes meant that the oledb would read the first row headers, hence know them. But it wasn't until I added a schema.ini file that I managed to query in this way.
Here's some more about schema.ini files

C# SQL string formatting

I am new to .net/C#. Coming from PHP and some Java, I am finding the new languages interesting and challenging.
I have an issue with a sql string
string query = #"select * from Users where role='member' and
SUBSTRinG(lname, 1, 1) = '"+querystring + "' ORDER BY lname ASC";
Which to me, looks fine. however when run my solution and output the query as it is not working, I get this as my output:
select * from Users where role='member' and SUBSTRinG(lname, 1, 1)
= ' O ' ORDER BY lname ASC
This is output into my Firebug console (the page that uses this query is accessed via AJAX).
Is their a reason my 's are being turned into their code version, ie '&#39'
Thanks
In C# you should be using SqlCommand to excute the query, and to prevent sql injection using the parameter collection.
Your query seems fine - The issue might be the way you are running it or the parameters being supplied. Update your question with more details on what you are expecting vs what is happening, include any error messages generated.
Below is a general guideline of how to get data from a sql table to a c# Data Table object.
SqlConnection conn = new SqlConnection("YourConnectionString");
SqlCommand cmd = new SqlCommand(#"select * from Users where role='member' and
SUBSTRinG(lname, 1, 1) = #query ORDER BY lname ASC");
cmd.Parameters.AddWithValue("#query", querystring);
DataTable resultTable = new DataTable();
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(resultTable);
} finally {
if (conn.State != ConnectionState.Closed) conn.Close();
}
Console.WriteLine(String.Format("Matched {0} Rows.", resultTable.Rows.Count));
For SQL injection protection:
You can provide escape sequence for single quotes by replacing them with two single quotes '' so that it will be treated as a single quote inside SQL strings. Otherwise it is considered as a start or end of the string value in SQL.
Replacing single quotes using ' in .net is also preferred but its better going with two single quotes.

how to update datagridview to database using c#?

I have a datagridview bound to a datasouce, bound to a datatable.
I want to create a button that when I click it, the database will be updated with the new parameters in the datagridview.
I've read some stuff about TableAdapter but I cant really find some good examples and explanations.
So if someone can give some information about tableadapter, it will help me a lot.
Also, if you think that you have a better solution for me regarding update the database, i'll be glad to know about that.
EDIT:
ok so i'm trying to use the mysqlcommandbuilder.
My code now looks like this:
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = new MySqlCommand("SELECT * from setups", sql_Class.myConnection);
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
cb.GetUpdateCommand();
da.Update(dt);
so now my error is in the da.Update(dt) and it says: "input string was not in the correct format".
I've created a loop that runs on all the parameters in the sql query and all the parameters values are null.
for (int i = 0; i <= cb.GetUpdateCommand().Parameters.Count - 1; i++)
{
Console.WriteLine(cb.GetUpdateCommand().Parameters[i].ParameterName + " " + cb.GetUpdateCommand().Parameters[i].Value);
}
I have values in the datatable, i've double checked it, but someone the parameters are null.
Any ideas why?
Managed to update my database in some "old fashion" method.
I'm just running on every single row in the datagridview and updates it using executenonquery.
I get all the parameters manually.
Example:
int setup_id = Convert.ToInt16(stam.Cells["setup_id"].Value);
string setup_name = stam.Cells["setup_name"].Value.ToString();
string mySqlQuery = "UPDATE setups SET setup_name='"+setup_name+"' WHERE setup_id="+setup_id;
MySqlCommand cm = new MySqlCommand(mySqlQuery, sql_Class.myConnection);
cm.ExecuteNonQuery();

Can we use variable for a table name in query?

Here in the code I am trying to retrieve information from a database and store it in a table. In query i have used a variable to specify a table, i am doing so because i want to use this single piece of code to retrieve information from various tables based on which table name the variable "a" contain but when i am executing this it's throwing me an exception. please help...
MyOleDbConnection.Open();
string a = "login";
string query = string.Format("select Email,Username,PhoneNo,Department from '{1}' where Email='{0}'", editrecordtextBox.Text,a);
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter();
da = new OleDbDataAdapter(query, MyOleDbConnection.vcon);
da.Fill(dt);
Note- this is just the part of the code, the exception is occuring in this code only.
Your code is in fact working correctly.
First of all, remove your single quotes around the table name. These mark a text, not an identifier or name.
I can imagine that login is a reseverd name you cannot use as plain text in your SQL. Depending on the database you can quote your tablename so it is recognizes as a name, not an reserved word.
For SQL-Server it would be done with [ and ]:
string query = string.Format("select Email,Username,PhoneNo,Department from [{1}] where Email='{0}'", editrecordtextBox.Text,a);
If you would give us your database, we could help.
the way that tested and Worked is something like Below as you see the Table Name is Variable Form i Make a query with concatenate 3 section together
string query = "SELECT TOP 1 * FROM M" + TableName.ToString() + " ORDER BY ID
DESC";

In Data grid Index out of range exception

In datagrid using C# while updating the sqlite from the form application I am getting index out of range exception .
Cannot find table 0
Below is my code
SQLiteConnection connection4 = new SQLiteConnection
(#"Data Source = C:\APTRABuilder.sqlite;Version =3");
connection4.Open();
string sql2 = "Update table set language1= '"
+ textBoxUpdate1.Text + "' where language2 = '"
+ textBox_Search.Text + "'";
SQLiteDataAdapter connect4 = new SQLiteDataAdapter(sql2, connection4);
DataSet ds4 = new DataSet();
connect4.Fill(ds4);
dataGridView.DataSource = ds4.Tables[0];
Error I am getting in dataGridView.DataSource = ds4.Tables[0];
There are no tables in the DataSet becasue the SQL is doing an UPDATE, not a SELECT, so there are no results to return.
You need to look at creating an UPDATE command for your Data Adapter.
You will also need to learn about adding values with Parameters.
Rather than trying to Fill the DataAdapter you are required to UPDATE the DataAdapter in this scenario. When you Fill a DataAdapter, you are populating the Adapter. To do this you use a SELECT command. These two methods are entirely different.
This Guide below will get you started in understanding Data Adapters better :-
http://msdn.microsoft.com/en-us/library/33y2221y.aspx
Good Luck.

Categories

Resources