I have this code where I put data to the DataTable from where I show everything on DataGridView.
But when I look it contains information which supposed to be in file but its repeated twice.
Code to retrieve data from mysql database:
MySqlDataAdapter mySqlDataAdapter;
DataSet DS0 = new DataSet();
DataTable DT0;
string gender;
private void Filter()
{
ViewG.DataSource = null;
ViewG.Rows.Clear();
command.CommandText = "SELECT * FROM `table2` WHERE s1q2 = #gender";
command.Parameters.Add("#gender", MySqlDbType.VarChar);
command.Parameters["#gender"].Value = gender;
DT0 = DS0.Tables.Add("1Filter");
mySqlDataAdapter = new MySqlDataAdapter(command.CommandText, connection);
connection.Open();
mySqlDataAdapter.SelectCommand = command;
mySqlDataAdapter.Fill(DS0.Tables["1Filter"]);
ViewG.DataSource = DS0.Tables["1Filter"];
connection.Close();
}
Initially, on the start it retrieves all information from the database code (SELECT * FROM table) and displays on the DataGridView. And it works fine, but when I try to use filters to retrieve only for example "Females" problem occurs.
For full data I use:
mySqlDataAdapter.Fill(DS0.Tables["Full"]);
ViewG.DataSource = DS0.Tables["Full"];
For Filtered data:
mySqlDataAdapter.Fill(DS0.Tables["1Filter"]);
ViewG.DataSource = DS0.Tables["1Filter"];
If I run query used for filter on the application startup it does not duplicate and show correctly.
EDIT: SOLVED
From the code posted here, gender string is not assigned any value. So, your query be applying any filter that you want.
Thanks for you effort I found where the problem was. I used temp table on MySql and for some reason server did not dropped this table after connection is closed. So on the new query it added same items on the same table....
Related
I haven been trying to figure this out all day and just couldn't find my mistake. I have an ms-access database and a c# program that is supposed to update the data in the db. Unfortunately I keep getting System.Data.OleDb.OleDbException: Syntaxerror in update statement.
I am using OleDbConnectionand OleDbDataAdapter and everything (except for one column) was working perfectly. I couldn't figure out why I kept getting the above mentioned error for that column (it was formatted just like the others -> text), so I deleted the column and created it again. Now I get the error for every single alteration I try to make.
public void changeFields(string id, string name, string famName, string department) {
DataSet myDS = new DataSet();
using (OleDbConnection conn = new OleDbConnection(connectionString)) {
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand("SELECT * FROM Table WHERE ID = '"+ id +"', conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
myDS.Tables["Table"].Rows[0]["Name"] = name;
myDS.Tables["Table"].Rows[0]["FamilyName"] = famName;
myDS.Tables["Table"].Rows[0]["Department"] = department;
adapter.Update(myDS, "Table");
conn.Close();
}
}
The names of the columns are correct and if I
Console.WriteLine(myDS.Tables["Table"].Rows[0]["Name"];
right before I try to update.
I actually get the correctly changed version. The error always occurs for line adapter.Update();
Is it possible that access rearranges or messes some index up when I insert a column into the database?
Help would be very much appreciated
I figured it out! The problem was that I had a reserved keyword as a column name. Now it all works perfectly fine
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();
Note: my office doesn't allow me to view YouTube and several other sites that probably have the answer to this question on them (they are blocked), which is why Googling the answer hasn't yielded results.
ComboBox code reference: found here
On my C# Form, I have filled a ComboBox with tables from a database (see below code), which returns the appropriate values and functions correctly:
public Form1()
{
InitializeComponent();
// Connection
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "CONNECTION STRING" // shortened for security and convenience
// Fill ComboBox with SQL Values
conn.Open();
SqlCommand cmbTables = new SqlCommand("SELECT name FROM sys.tables", conn);
SqlDataReader read = cmbTables.ExecuteReader();
DataTable cmbData = new DataTable();
cmbData.Columns.Add("name", typeof(string));
cmbData.Load(read);
cmb1.DisplayMember = "name";
cmb1.DataSource = cmbData;
conn.Close();
}
After the ComboBox loads the tables (which works), the application then selects a table and clicks a button that loads the table, which is selected. This is where the code errors:
private void button1_Click(object sender, EventArgs e)
{
using (var connection = Utilities.GetConnection())
{
string table = Convert.ToString(txt1.Text);
string cmb1Value = Convert.ToString(cmb1.SelectedItem);
// Stored Procedure
SqlCommand select = new SqlCommand("EXECUTE STOREDPROCEDURE" + cmb1Value, connection); // shortened for security and convenience
select.Parameters.Add(new SqlParameter(cmb1Value, table));
// Data View
SqlDataAdapter ad= new SqlDataAdapter(select);
ad.SelectCommand = select;
DataTable dt = new DataTable();
ad.Fill(dt); // this generates the error "Incorrect Syntax Near '.'"
BindingSource b = new BindingSource();
b.DataSource = dt;
dGrid.DataSource = b;
ad.Update(dt);
connection.Close();
}
}
Even though the ComboBox loads the appropriate values, from the above code, I may be missing something which attaches those values to the SELECT stored procedure (all it does is call SELECT statement through a variable passed to it). The error, "Incorrect Syntax Near '.'" looks like a SQL Server error that I've seen, but can't remember how I generate it (this is how I usually troubeshoot where the TSQL code went wrong).\
Stored Procedure Related code:
C#:
SqlCommand select = new SqlCommand("EXECUTE STOREDPROCEDURE " + cmb1Value, connection);
TSQL:
CREATE PROCEDURE [STOREDPROCEDURE]
#TableName VARCHAR(250)
AS
BEGIN
DECLARE #sql NVARCHAR(MAX)
SET #sql = N'SELECT TOP 100 *
FROM ' + #TableName
EXECUTE(#sql)
END
-- Note this works in SSMS without a problem.
The above code is incorrect, and when I tweak the TSQL code, I generate similar errors, telling me that somewhere I am missing a conversion, or another variable because SQL Server isn't seeing these table values returned by the SELECT (first block of code). I can ascertain this because I have a second ComboBox that uses similar code EXCEPT that I populated the ComboBox with manual values, and it connects to the tables in the database with no error. So, the ComboBox, which grabs values from the database, that you see above, does not function correctly.
For instance, if I only add the below line of code to the code, I receive an error that it can't find the database "EXECUTE STOREDPROCEDURE System'
select.CommandType = CommandType.StoredProcedure;
However, System isn't a part of anything, so where did that come from? It never errored with this code on the manual ComboBox, as it had no trouble finding the database (using the same connection string, server and database!).
If I try to use a TSQL parameter, such as:
SqlCommand select = new SqlCommand("EXECUTE stp_ReturnTable #p", scon);
select.Parameters.Add(new SqlParameter("#p", cmb1Value));
Suddenly, it can't find the stored procedure. Again, the connection strings are identical for the manual ComboBox and the dynamic ComboBox.
I think the code behind the dynamic ComboBox is wrong. When I'm out of the office, I'll review some videos with detailed demonstrations on how to create a dynamic ComboBox from a database and I have a hunch that a system object is in the way (based on the System error, which exists nowhere in my code, as well as it suddenly being unable to find the database or procedure).
The missing key point in your code is the CommandType.
Without the proper set of this property the default is CommandText and thus the Framework expects a statement that starts with SELECT/INSERT/UPDATE/DELETE etc....
using (var connection = Utilities.GetConnection())
{
string table = Convert.ToString(txt1.Text);
string cmb1Value = Convert.ToString(cmb1.SelectedItem);
// Stored Procedure
SqlCommand select = new SqlCommand("STOREDPROCEDURE", connection);
select.Parameters.Add(new SqlParameter("#TableName", cmb1Value));
// That's the key to let ADO.NET accept the previous CommandText as valid.
// If you omit this the CommandText is assumed to be a SELECT/UPDATE/DELETE etc..
select.CommandType = CommandType.StoredProcedure;
// Data View
SqlDataAdapter ad= new SqlDataAdapter(select);
DataTable dt = new DataTable();
ad.Fill(dt);
BindingSource b = new BindingSource();
b.DataSource = dt;
dGrid.DataSource = b;
}
EDIT Having seen the code of the SP then you could simply set the SqlParameter name to the constant #TableName and pass the value extracted from the combobox as the value to be used inside the SP
EDIT I have looked again at your code and I suspect that the culprit is the line
string cmb1Value = Convert.ToString(cmb1.SelectedItem);
Looking at how you have filled your combo, this line, doesn't return the tablename as you expect, but the generic string System.Data.DataRowView because the DataSource of the combo is a DataTable and not a string collection. You should try to change that line in this way
DataRowView rw = cmb1.SelectedItem as DataRowView;
if(rw != null)
{
string cmbValue1 = rw["name"].ToString();
....
And yes, your code should work also without the CommandType.StoredProcedure line because the text EXECUTE sp param is recognized as a valid sql commandtext (but why do you use it when a direct call to the storedprocedure could be optimized for reuse?)
I have a stored procedure called "WEB_SEL_SECURITY_QUESTIONS" in my sql database which returns a table as follows.
SEQURITY_QUESTIONS_KEY, KEYCODE, QUESTION
I need to populate a html selectbox with the list of questions I get from executing the above procedure.
This is what I have tried
String s = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
SqlConnection con = new SqlConnection(s);
con.Open();
SqlDataAdapter myAdepter = new SqlDataAdapter("WEB_SEL_SECURITY_QUESTIONS", con);
myAdepter.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
myAdepter.Fill(ds, "WEB_SEL_SECURITY_QUESTIONS");
String questions = ds.Tables["WEB_SEL_SECURITY_QUESTIONS"].Rows[]["QUESTION"].ToString();
securityQuestion1.DataSource = questions;
securityQuestion1.DataBind();
But this populates the select box with only one record and it generates the list items in such a way that, only one character per list item and only the first record.
You could try:
securityQuestion1.DataSource = ds.Tables["WEB_SEL_SECURITY_QUESTIONS"];
securityQuestion1.DataTextField = "QUESTION";
securityQuestion1.DataValueField = "KEYCODE"; // Or whatever the value field needs to be.
securityQuestion1.DataBind();
What your first attempt was doing is just taking that single value from one question and using that as the entire data source. So what you need to aim for is make the whole security questions table the data source, and then give it hints as to what columns to use for value and display (DataTextField, DataValueField).
I am trying to populate some text boxes on a form with data pulled from MySQL into a data set.
I cant seem to get the code right and could use some help
string ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection;
MySqlDataAdapter adapter;
DataTable DTItems;
connection = new MySqlConnection(ConnectionString);
try
{
//prepare query to get all records from items table
string query = "select * from spt_proposal where fr_Numer = "+ a+"";
//prepare adapter to run query
adapter = new MySqlDataAdapter(query, connection);
DataSet DS = new DataSet();
//get query results in dataset
adapter.Fill(DS);
textBox5.Text = DS.Tables[0].Rows[0].ToString();
This does not hit the text box at all.
a in the query is a variable that is pulled from a different form
and the query should pull 32 different things from the database in a row
There are about 9 text boxes on the form that i will have to fill with different data from this row.
Anyone have a better way to do this?
Brent
Try:
textBox5.Text = DS.Tables[0].Rows[0][0].ToString();
Remember, that a Table is pretty much a two dimensional array. Your code literally gets to the 1st row in the DataSet, but doesn't take into account the Column.