I'm using VS 2012 C#. I'm trying to loop through datasets to get information from an Access database. I have a combobox that when an item is selected it should print out all the data for that given scenario. For some the the values in the combobox I get the error, "The SelectCommand property has not been initialized before calling 'Fill'." But for some of the other values I don't and the information is retrieved without an issue. Here is all the necessary code,
con2.Open();
ad2 = new OleDbDataAdapter(query, con2);
ad2.Fill(ds2, "AC_SCENARIO");
con2.Close()
try
{
string end = "ENDDATE";
string start = "START";
foreach (DataRow drRow in ds2.Tables[0].Rows)
{
for (int i = 0; i <= ds2.Tables[0].Columns.Count; i++)
{
string qual0 = ds2.Tables["AC_SCENARIO"].Rows[i]["QUAL0"].ToString();
string qual1 = ds2.Tables["AC_SCENARIO"].Rows[i]["QUAL1"].ToString();
string qual2 = ds2.Tables["AC_SCENARIO"].Rows[i]["QUAL2"].ToString();
string qual3 = ds2.Tables["AC_SCENARIO"].Rows[i]["QUAL3"].ToString();
string qual4 = ds2.Tables["AC_SCENARIO"].Rows[i]["QUAL4"].ToString();
//HERE IS A SAMPLE QUERY
if (qual0 != null && (string)comboBox1.SelectedItem == qual0)
{
ad.SelectCommand = new OleDbCommand("SELECT b.RSV_CAT, b.SEQNUM, b.LEASE, b.WELL_ID, a.QUALIFIER, a.KEYWORD, a.EXPRESSION FROM [AC_ECONOMIC] a INNER JOIN [AC_PROPERTY] b on a.PROPNUM=b.PROPNUM WHERE a.KEYWORD = '"
+ end + "' AND (a.QUALIFIER = '" + qual0 + "' OR a.QUALIFIER IS NULL) AND NOT a.EXPRESSION Like '%[/#]%'", con);
}
ds.Clear();
ad.Fill(ds); //The SelectCommand property has not been initialized before calling 'Fill'.
//ERROR OCCURS HERE
con.Open();
ad.SelectCommand.ExecuteNonQuery();
con.Close();
EDIT: HERE IS THE con CODE
String filePath = textBox1.Text;
con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath);
I have more queries such as those listed for another dataset and then I merge the two datasets together and output them to a datagridview. The error occurs on the line ad.Fill(ds); If anyone can explain this issue to me or has any help that would be great.
Columns collection of DataTable is zero based index and is one less then Count, the loop should be one less then number of columns as first column is at 0 index and last column is columns count-1. You can use < instead of <= in loop condition to iterate from zero to Count-1.
Change
for (int i = 0; i <= ds2.Tables[0].Columns.Count; i++)
To
for (int i = 0; i < ds2.Tables[0].Columns.Count; i++)
Creation of con is also not present in the code you have in OP
the problem is probably here
if (qual0 != null && (string)comboBox1.SelectedItem == qual0)
In some scenarios the if loop turns out to be true and ad.SelectCommand will get initialized.
EDIT
Are you sure the Select Command is forming correctly for every values of qual0.
Please try using named parameters while forming the query . the qual variable might be having some ' in it that prevent your query getting formed correctly..
EDIT
qual0.Replace("'","\"");
You've not provided a default case for if qual0 is null.
I'm going to assume that you do this multiple times and it's not just the one qual variable you check and build a statement for, if that's the case then you might be better off refactoring to something like this:
if (qual0 != null && (string)comboBox1.SelectedItem == qual0)
{
ad.SelectCommand = new OleDbCommand("SELECT b.RSV_CAT, b.SEQNUM, b.LEASE, b.WELL_ID, a.QUALIFIER, a.KEYWORD, a.EXPRESSION FROM [AC_ECONOMIC] a INNER JOIN [AC_PROPERTY] b on a.PROPNUM=b.PROPNUM WHERE a.KEYWORD = '"
+ end + "' AND (a.QUALIFIER = '" + qual0 + "' OR a.QUALIFIER IS NULL) AND NOT a.EXPRESSION Like '%[/#]%'", con);
}
if (ad.SelectCommand != null)
{
if (!String.IsNullOrEmpty(ad.SelectCommand.CommandText))
{
ds.Clear();
ad.Fill(ds);
}
}
Related
Since yesterday I am trying to get this value (see image), I have tried to use "mysqlreader, executescalar and more", but I cannot get the number of lines.
What I want to do is this:
If the result is 0 it does nothing, if equal to 1 it must show an image, if greater than 1 it must show another image
ex code 1
private void patient()
{
if (OpenEventMissionData.Rows.Count != 0)
{
foreach (DataGridViewRow row in OpenEventMissionData.Rows)
{
string idevent = row.Cells[1].Value.ToString();
string sql = "SELECT COUNT(*) FROM patient INNER JOIN event WHERE patient.ID_EVENT = " + "'" + idevent + "'" + "AND evento.EVENT_OPEN = 1;";
MySqlConnection connection = new MySqlConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
MySqlCommand cmd = new MySqlCommand(sql, connection);
connection.Open();
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
DataGridViewButtonColumn patient = new DataGridViewButtonColumn();
OpenEventMissionData.Columns.Add(new PatientColumn());
}
}
}
}
I tried adding the code that told me #oldDog, but the result is always 6
ex code 3
NEW EDIT:
In fact 6 lines appear.
phpmyadmin
Your problem here is you are using HasRows. Since you are doing SELECT COUNT(*) you will always have one row which will contain the count, even if the count is zero. Instead you could use:
if (Convert.ToInt32(reader[0]) > 0)
I’ve got a problem with this SELECT. When I execute it on MS Access, the result is returning right and fully. When I try to execute it via C#, the same query returns nothing. The previous variant of the SELECT was realized by adapter to show the result of select in dataGridView. But when I execute it, I get only an empty table with column names.
private void getByObjectAndPollutant(string Object, string Pollutant,
int firstYear, int lastYear)
{
List<string> result = new List<string>();
// line breaks added without concatenation, for readability.
cmd = new OleDbCommand("SELECT object_name, p_name, mpc, emission_concentration,
[year] FROM Pollutants INNER JOIN (Objects INNER JOIN Emissions
ON Objects.o_id = Emissions.e_o_id) ON Pollutants.p_id = Emissions.e_p_id
WHERE (object_name = '" + Object + "' AND p_name = '" + Pollutant + "' AND
[year] BETWEEN " + firstYear + " AND " + lastYear + ") ;", con);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read()) {
var myString = reader.GetString(0);
result.Add(myString);
richTextBox1.Text += myString;
}
con.Close();
}
This is how I call it in program:
private void button5_Click(object sender, EventArgs e) {
string localObject = comboBox5.Text.ToString();
string localPollutant = comboBox4.Text.ToString();
int localFirstYear = Convert.ToInt32(comboBox6.Text);
int localLastYear = Convert.ToInt32(comboBox7.Text);
getByObjectAndPollutant(localObject,localPollutant,localFirstYear,localLastYear);
}
This is SELECT query in MS Access:
SELECT object_name, p_name, mpc, emission_concentration, year
FROM Pollutants
INNER JOIN (Objects
INNER JOIN Emissions ON Objects.o_id=Emissions.e_o_id)
ON Pollutants.p_id=Emissions.e_p_id
WHERE object_name="some name" And p_name="some name" And year Between 2011 And 2015;
And this was the previous code of method:
private void getByObjectAndPollutant(string Object, string Pollutant, int firstYear,
int lastYear)
{
con.Open();
DataTable dt = new DataTable();
adapt = new OleDbDataAdapter(this long select);
adapt.Fill(dt);
dataGridView2.DataSource = dt;
con.Close();
}
Main reason I use reader or adapter is to get the result of SELECT query. Is this SELECT returning something? When this works I will then code method to draw chart based on SELECT.
Could be the combos/dropdownlists. Weirdly, comboBox5.Text returns the selected value, not the text.
Try changing to
string localObject = comboBox5.SelectedItem.Text;
string localPollutant = comboBox4.SelectedItem.Text;
Hello! Finally I find the solution. The main aim of SELECT was to get some data from DataBase, but while I getting it I use not ID of an
Item, I use Name of an Item and it return no result. So i think let me
try to make condition with ids.
So the code of working function:
private void getByObjectAndPollutant(int Object, int Pollutant, int firstYear, int lastYear)
{
con.Open();
DataTable dt = new DataTable();
adapt = new OleDbDataAdapter("SELECT mpc, emission_concentration FROM Pollutants INNER JOIN (Objects INNER JOIN Emissions ON Objects.o_id = Emissions.e_o_id) ON Pollutants.p_id = Emissions.e_p_id WHERE Objects.o_id=" + Object + " AND Pollutants.p_id=" + Pollutant + " AND Emissions.[year] BETWEEN " + firstYear + " AND " + lastYear + ";", con);
adapt.Fill(dt);
dataGridView2.DataSource = dt;
con.Close();
}
The code of working function call:
private void button5_Click(object sender, EventArgs e)
{
int localObject = Convert.ToInt32(comboBox4.SelectedValue.ToString());
int localPollutant = Convert.ToInt32(comboBox5.SelectedValue.ToString());
int localFirstYear = Convert.ToInt32(comboBox6.SelectedItem.ToString());
int localLastYear = Convert.ToInt32(comboBox7.SelectedItem.ToString());
getByObjectAndPollutant(localObject,localPollutant,localFirstYear,localLastYear);
}
And in result DataGridView I get the right data I`m happy so much!!! Thanks to ALL of You who was trying to help me!!!
There are 2 rows in my table and I'm receiving values within my site as follows:
I should only be receiving 2 rows so I'm not sure what I've done wrong with my code?
if (binForm.Rows.Count != 0)
{
int rowCounter = binForm.Rows.Count;
int increment = 0;
while (rowCounter > 0)
{
tableData.Append("<tr><td>" + binForm.Rows[increment]["binType"].ToString() + "</td><td>" + binForm.Rows[increment]["binColour"].ToString() + "</td><td>" + binForm.Rows[increment]["date"].ToString() + "</td><tr>");
increment++;
rowCounter--;
}
}
This is how the form is generated:
DataTable binForm = new DataTable();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter("SELECT bin.binType, bin.binColour, missedbin.date FROM bin INNER JOIN missedbin ON missedbin.address_addressID=bin.address_addressID WHERE '" + sessionVarAddress.ToString() + "' = bin.address_addressID ", connect);
dataAdapter.Fill(binForm);
here is the actual data in the bin table.
and missedbin table.
EDIT: It seems as though as suggested my sql query is incorrect as it is returning 4 rows.
The problem will be the join, not this snip-it of code.
if you join on a field with 2 entries the same, it will double up as per this example. please go back and check your query.
guys i have an SQL statement returning more than 1 value.
I am trying to use the StreamReader to get the values into an array as below
string sql = "select distinct COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME=' " + table + "' and CONSTRAINT_NAME like 'PK_%'";
SqlConnection conn2 = new SqlConnection(cnstr.connectionString(cmbDatabase.Text));
SqlCommand cmd_server2 = new SqlCommand(sql);
cmd_server2.CommandType = CommandType.Text;
cmd_server2.Connection = conn2;
conn2.Open();
//reader_sql = new StreamReader();
SqlDataReader reader_sql = null;
string[] colName = new string[200];
reader_sql = cmd_server2.ExecuteReader();
while (reader_sql.Read());
for (int rr = 0; rr < 20; rr++)
{
colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}
It is not working, what am I doing wrong guys ?
You've got a stray ; turning your while into a tight loop, so instead try:
while (reader_sql.Read())
for (int rr = 0; rr < 20; rr++)
{
colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}
You get the exception because
while (reader_sql.Read());
should be
while (reader_sql.Read())
{
for (int rr = 0; rr < 20; rr++)
{
colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}
}
Perhaps you should remove the semicolon at the end of Read
while (reader_sql.Read())
{
for (int rr = 0; rr < 20; rr++)
colName[rr] = reader_sql["COLUMN_NAME"].ToString();
}
However, if your intention is to retrieve the columns belonging to the primary key, your code is wrong because you add 20 times the same primary key column, then repeat the same for the remaining columns ending with an array of 20 strings all equals to the last column in the primary key set. I think you should change your code to use a List(Of String) instead of a fixed length array and let the reader loop correctly on the primary key columns retrieved
List<string> pks = new List<string>();
while (reader_sql.Read())
{
pks.Add(reader_sql["COLUMN_NAME"].ToString());
}
EDIT: I have just noticed that your query contains a space before the table name. The string concatenation then produces an invalid table name, the query is syntactically right but doesn't return any data
string sql = "select distinct COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
"where TABLE_NAME='" + table + "' and CONSTRAINT_NAME like 'PK_%'";
^ space removed here
And while you are at it, remove the string concatenation and use a parameterized query.....
string sql = "select distinct COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
"where TABLE_NAME=#tName and CONSTRAINT_NAME like 'PK_%'";
SqlCommand cmd_server2 = new SqlCommand(sql, connection);
connection.Open();
cmd_server2.Parameters.AddWithValue("#tName", table);
I am trying to bind sql data on textboxes against reading data from label my code is as below:
string sql1 = " select openbal from AccountMast where accname='" + comboBox1.Text + "' and companyID='" + label4.Text + "'";
SqlDataAdapter dap1 = new SqlDataAdapter(sql1, con);
DataSet ds1 = new DataSet();
dap1.Fill(ds1);
for (int p = 0; p < ds1.Tables[0].Rows.Count; p++)
{
if (label11.Text == "Dr")
{
txtopenbaldr.Text = Convert.ToString(ds1.Tables[0].Rows[p]["openbal"]);
}
if (label11.Text == "Cr")
{
txtopenbalcr.Text = Convert.ToString(ds1.Tables[0].Rows[p]["openbal"]);
}
}
//Label11 Bind by Sql.
string sql10 = " select obcat from AccountMast where accname='" + comboBox1.Text + "' and companyID='" + label4.Text + "'";
SqlDataAdapter dap10 = new SqlDataAdapter(sql10, con);
DataSet ds10 = new DataSet();
dap10.Fill(ds10);
for (int p = 0; p < ds10.Tables[0].Rows.Count; p++)
{
label11.Text = Convert.ToString(ds10.Tables[0].Rows[p]["obcat"]);
}
The label11 bound by sql data and it should display text "Dr" OR "Cr" at a time.
but it's not working as the label11.text not support for bind the data onto textboxes
I have two textboxes as below:
Opening Balance/Debit Opening Balance/Credit
txtopenbaldr.Text txtopenbalcr.Text
There are two textboxes which can databind on above condition: Remember only one textbox should be bind as per condition.
I am trying the trick but it's fail. Suggest the solution.
I'm assuming that you simply appended the code for label11.text at the end of your message, but that in reality label11.text is assigned before you try to set txtopenbaldr.Text or txtopenbalcr.Text.
If that's the case, I would make sure that label11.Text actually has the value Dr or Cr, and not DR or CR, as the comparisons will be case-sensitive.