I have a working query for statistics. It is output to datagridview. Next, I want to arrange the display of statistics by a graph. But the graph is not displayed.
here is what it looks like
here is my code:
void FillChartAnimalsStat()
{
SqlConnection con = new SqlConnection(#"Data Source=Anesia;Initial Catalog=WEP_Clinic_Db;Integrated Security=True");
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select kind_definition, count(*) as amount" +
"\r\nfrom Kinds_of_animals inner join Patients on Kinds_of_animals.kind_id = Patients.kind_id " +
"\r\ninner join Visits on Patients.patient_id = Visits.patient_id group by Kinds_of_animals.kind_definition order by amount desc", con);
da.Fill(dt);
chart1.Series["Statistics"].XValueMember = "kind_definition";
chart1.Series["Statistics"].YValueMembers = "amount";
chart1.Titles.Add("Види тварин на прийомах за частотою їх розподілу");
}
I did the video tutorial, repeated everything in exactly the same way, but there is no result. What am I missing?
Problem found - it was necessary to add DataSource
Related
I am new to C# and need some guidance!
short summary:
I have an application with few forms that is connected to the Access database. Everything is working fine! The user can select the needed item from the combo box that is shown in the label on the next form. Additionally the elements of the table are shown in the datagridview2 on the same form. Every item from the combo box is connected to a different table in the Access database:
private void frmData_Load(object sender, EventArgs e)
{
lblItem.Text = Item;
string connectionString = null;
OleDbConnection con;
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\".\\Database_Example.accdb\"";
con = new OleDbConnection(connectionString);
if (lblItem.Text == "X")
{
OleDbCommand cmd2 = new OleDbCommand("SELECT ID, Column1, Column2 FROM X", con);
OleDbDataAdapter sda = new OleDbDataAdapter(cmd2);
DataTable td = new DataTable();
sda.Fill(td);
dataGridView2.DataSource = td;
}
if (lblItem.Text == "Y")
{
OleDbCommand cmd = new OleDbCommand("SELECT ID, Column1, Column2 FROM Y", con);
OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
DataTable td = new DataTable();
sda.Fill(td);
dataGridView2.DataSource = td;
}
}
Now I want to use my application to add new tables to the database. Therefore there are bunch of different approaches on the web.
Problem: I´m looking for an option to automatically create new if-statements once I´ve added new tables in the database. For example for items "Z"; "A"; "B"; ...
Is there a way to do it? Or do I need a different approach?
Greetings :)
We get this question a few times a month and the answer is always the same:
You really need ONE table, with an additional column for your Z, A, B, etc. Make this the first field of the primary key.
Now this:
if (lblItem.Text == "X")
{
OleDbCommand cmd2 = new OleDbCommand("SELECT ID, Column1, Column2 FROM X", con);
OleDbDataAdapter sda = new OleDbDataAdapter(cmd2);
DataTable td = new DataTable();
sda.Fill(td);
dataGridView2.DataSource = td;
}
// etc
Becomes this:
var td = new DataTable();
using (var con = new OleDbConnection("connection string here"))
using (var cmd = new OleDbCommand("SELECT ID, Column1, Column2 FROM MyTable WHERE Key = ? ", con))
using (var sda = new OleDbDataAdapter(cmd2))
{
cmd.Parameters.Add("?", OleDbType.NChar, 3).Value = lblItem.Text;
sda.Fill(td);
}
No if statement required.
Additionally, do NOT try to re-use your connection object throughout a form instance like that. It really is more efficient to create a new connection for each call to the database.
I connot able to filter the current user record. I want to display the data of current user only. But I did not understand how to handl query.
here is the ss of login.
As I selected Student, and username =50 and pass=50 ,
and when i press he show button this will display all the record but i want only current user data :
here is the code :
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
OleDbDataAdapter sda = new OleDbDataAdapter(#"SELECT student.s_id, student.f_name, student.l_name, student.email, student.address, course.c_id, course.cname, resultdate.resultgrade FROM ((student INNER JOIN resultdate ON student.s_id = resultdate.s_id) INNER JOIN course ON resultdate.c_id = course.c_id)", conn);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
//dataGridView1.Text = dt.Rows.Count.ToString();
conn.Close();
Paste this code in your combobox.
con.Open();
string query = “ select* from student where student.s_id = ’”
+combobox1.SelectedItem.ToString() + “’”;
OleDbDataAdapter sda = new OleDbDataAdapter(query, con);
OleDbCommandBuiler builer = new OleDbCommandBuiler(da);
var ds = new DataSet();
sda.Fill(ds);
datagridview1.Datasource = ds.Table[0];
conn.Close();
I am trying to update my data in a SQL Server database through C#. I am getting updated. But the problem is the data is updated twice.
For example I have 10 (int) in my balance and if I add another 10, it turns to 30.
Any help would be appreciated.
Here is my code:
protected void LoginClick(object sender, EventArgs e)
{
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
}
I would like to rectify few mistakes in your code,
DataTable is not needed to execute the update query, ExecuteNonQuery will do the job
The adapter.Fill and ExecuteNonQuery do the same job here and that's why your updates happening twice
Make use of parameterization while dealing with user inputs to avoid exceptions
For parsing integers use int.TryParse instead for Convert.ToInt32
I think the following code would help you to do the same function in a smarter way:
int currentBalance = 0;
if(int.TryParse(txtAdd.Text, out currentBalance))
{
string querSql = "Update [Order] set Balance = Balance + #balance," +
" Card = #card where email = #email"
using (SqlConnection dbConn = new SqlConnection("connectionString here"))
{
dbConn.Open();
using (SqlCommand sqlCommand = new SqlCommand(querySql, dbConn))
{
sqlCommand.Parameters.Add("#balance", SqlDbType.int).value = currentBalance;
sqlCommand.Parameters.Add("#card", SqlDbType.VarChar).value = card.Text;
sqlCommand.Parameters.Add("#email", SqlDbType.VarChar).value = email;
sqlCommand.ExecuteNonQuery();
}
}
}
Please note: YOu are parsing the balance as an integer value, so I assume the column Balance is an integer field in the database, if not make use of corresponding datatype for the parameter #balance also update the parsing technique
As per the documentation:
SqlDataAdapter(SqlCommand)
Initializes a new instance of the SqlDataAdapter class with the specified SqlCommand as the SelectCommand property.
What is going wrong in your code?
Actually you are passing SqlDataAdapter your update query as the Select command. So now when you will use this instance of SqlDataAdapter to Fill your datatable then actually you are executing your Update command. Look at the following code along with comments to see what is going wrong:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);//The Select command for SqlDataAdapter
//is actually now the update command specified by cmd instnace of SqlCommand
DataTable dt = new DataTable();
sda.Fill(dt);//here SqlDataAdapter will execute it's Select command which is actually set
//to an update statement so your record will be updated
int i = cmd.ExecuteNonQuery();//and here again the update command is being executed now
//directly using the SqlCommand cmd instance and thus your record gets updated twice
con.Close();
Fixed Code:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
//Create a new SqlComamnd
SqlCommand selectCommand = new SqlCommand("Select * from [Order]");
//Put the newly created instance as SelectCommand for your SqlDataAdapter
SqlDataAdapter sda = new SqlDataAdapter(selectCommand);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
Hope this help and do have a look at the documentation for better understanding of the SqlDataAdapter and DataTable. Thanks.
In textbox I am fetching city name and when I select any city name, information related to that city should display on datagridview, to fetch other information about the state I used a foreign key because state table is different and its information is stored in another table so I fetch that information from foreign key state_id. Here is my code
DataTable dt = new DataTable();
SqlDataAdapter tda = new SqlDataAdapter("SELECT a1.type,a1.state_id,a1.desc1,a1.from_date,a1.to_date,a1.expr1005 FROM item_rate a1 FULL OUTER JOIN item_rate_state a2 ON a1.state_id=a2.state_id WHERE state_name='" + textBox2.Text + "'", scon);
tda.Fill(dt);
dataGridView2.DataSource = dt;
The query seems a little wrong
it should be
SqlDataAdapter tda = new SqlDataAdapter("SELECT a1.type,a1.state_id,a1.desc1,a1.from_date,a1.to_date,a1.expr1005 FROM item_rate a1 FULL OUTER JOIN item_rate_state a2 ON a1.state_id=a2.state_id WHERE a2.state_name='" + textBox2.Text + "'", scon);
i would suggest you to use SqlCommand and add parameters to query proper way as your code is vulnerable to sql injection!
Answer as per the comment.
since you do now want to show any record when textbox is empty simple on TextChanged event do this
if (!String.IsNotNullOrEmpty(textBox2.Text))
{
DataTable dt = new DataTable();
SqlDataAdapter tda = new SqlDataAdapter("SELECT a1.type,a1.state_id,a1.desc1,a1.from_date,a1.to_date,a1.expr1005 FROM item_rate a1 FULL OUTER JOIN item_rate_state a2 ON a1.state_id=a2.state_id WHERE a2.state_name='" + textBox2.Text + "'", scon);
tda.Fill(dt);
dataGridView2.DataSource = dt;
}
You have Try like this
Set textBox2.AutoPostBack="True" in design page
protected void textBox2_TextChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
SqlDataAdapter tda = new SqlDataAdapter("SELECT a1.type,a1.state_id,a1.desc1,a1.from_date,a1.to_date,a1.expr1005 FROM item_rate a1 FULL OUTER JOIN item_rate_state a2 ON a1.state_id=a2.state_id WHERE state_name='" + textBox2.Text + "'", scon);
tda.Fill(dt);
dataGridView2.DataSource = dt;
}
I have a hyperlink which should print information from sql database.But I'm not able to know how to give that hyperlink value to sql query.
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlDataAdapter ADP = new SqlDataAdapter("select * from News where Headlines= au_id", conn);
I want to get value au_id dynamically can anybody help me with this after clicking on the hyperlink.
Its like when i click on the headlines i should get the corresponding news.
First of all, you should use a LinkButton instead of a Hyperlink control as hyperlink redirects the page to a specified URL. But the LinkButton has a Click Event handler. On that click you can get the ID.
Your query will be look like...
SqlDataAdapter ADP = new SqlDataAdapter("select * from News where Headlines = " + au_id, conn);
But It would be better if you use a Parameterized query to save yourself from a SQL Injection Attack.
SqlDataAdapter ADP = new SqlDataAdapter("select * from News where Headlines = #au_id", conn);
ADP.SelectCommand.Parameters.Add("#au_id", System.Data.SqlDbType.Int, 4, "au_id");
I'm not sure what do you exactly want, but here is simple example :
using ( command = new SqlCommand( ("select * from News where Headlines=" + au_id ), conn) //send au_id as string variable
{
DataTable outDT = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(outDT);
return outDT; // Your DataTable
}