How To Bind A DataTable To MS Chart - c#

this is myCode:
private void frmChart_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (SqlConnection Con = new SqlConnection(cs))
{
SqlCommand cmdSum = new SqlCommand("Select distinct(UserName),sum(Value) from mytable group by UserName",Con);
Con.Open();
SqlDataReader reader = cmdSum.ExecuteReader();
chart1.DataBindTable(reader,"sum(Value)");
}
foreach (Series series in chart1.Series)
{
series.CustomProperties = "DrawingStyle=LightToDark";
}
}
It shows me an error in chart1.DatabindTable. also I try another method but I could not handle it.

If all you're trying to do is to bind a data table, then just do this:
private void Form1_Load(object sender, EventArgs e)
{
string sql = "your sql here";
SqlDataAdapter adapter = new SqlDataAdapter(sql, connectionString);
DataTable dt = new DataTable();
adapter.Fill(dt);
chart1.DataBindTable(dt.DefaultView, "UserName");
}
Note when calling DataBindTable you have to use "UserName" (xField). Not Value or Sum(Value).

check you values into reader.. if you have values,
try replacing
chart1.DataBindTable(reader,"sum(Value)");
with
chart1.DataBindTable(reader,"Value");
once you sum up values into query you need not to mention sum again, your Value parameter will have sum
Edit --- Updated Code..
private void frmChart_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (SqlConnection Con = new SqlConnection(cs))
{
SqlCommand cmdSum = new SqlCommand("Select distinct(UserName),sum(Value) from mytable group by UserName", Con);
Con.Open();
SqlDataReader reader = cmdSum.ExecuteReader();
while (reader.Read())
{
chart1.DataBindTable(reader, reader["Value"]);
}
}
foreach (Series series in chart1.Series)
{
series.CustomProperties = "DrawingStyle=LightToDark";
}
}

Related

Get Values from Database based on one textbox in a registration form

I am making a basic web form with basic fields like name, email, number.
I just want, when i enter the number, rest of the fields are populated in the other textboxes based on that number from sql server.
Any help would be appreciated.
Code is as follows :
string ConnectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
string cmd = "IF NOT EXISTS(Select * from tbl_registration where Email = #Email OR MobileNo = #MobileNo) insert into tbl_registration values(#FirstName, #LastName,#Email,#MobileNo,#Address_1,#Address_2,#City,#State)";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using(SqlCommand com = new SqlCommand(cmd, con))
{
com.Parameters.AddWithValue("#FirstName", txtfname.Text.Trim());
com.Parameters.AddWithValue("#LastName", txtlname.Text);
com.Parameters.AddWithValue("#Email", txtemail.Text);
com.Parameters.AddWithValue("#MobileNo", txtmob_no.Text);
com.Parameters.AddWithValue("#Address_1", txtaddress1.Text);
com.Parameters.AddWithValue("#Address_2", txtaddress2.Text);
com.Parameters.AddWithValue("#City", txtcity.Text);
com.Parameters.AddWithValue("#State", txtstate.Text);
con.Open();
int success = com.ExecuteNonQuery();
if (success > 0)
{
Response.Write("<script>alert('Registration successfull')</script>");
}
else
{
Response.Write("<script>alert('Registration Not Sucessfull')</script>");
}
}
}
}
You should write the method definition as shown below on the text box changed event.
This is not the complete query answer. Here is a reference for you.
using (SqlConnection conn = new SqlConnection(CSs))
{
string query = "Your SQL Query here";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "sometablename");
firstnametext.Text = Convert.ToString(ds.Tables["sometablename"].Rows[0]["Firstname"]);
}
Here you need to properly handle the null for the data table.

How to retrieve data from database in label

I wanat to retrieve student ID from database. Here is my code what i have tried but it is not displaying anything.
Thanks...
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True");
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
string str = "select * from StRecords where StID='" + Session["login"] + "'";
SqlCommand com = new SqlCommand(str, con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Label11.Text = dt.Rows[0]["StID"].ToString();
}
}
If you want to take just StudentId from the database, then you just select that column and use ExecuteScalar property.
Code
protected void Button2_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True"))
{
con.Open();
string str = "select [StID] from StRecords where StID = #stdId;";
using (SqlCommand com = new SqlCommand(str, con))
{
com.Parameters.AddWithValue("#stdId", Session["login"]);
Label11.Text = com.ExecuteScalar().ToString();
}
}
}
Also always use parameters instead passing the value in single quotes to avoid SQL injection attack.
Also try to give the connection string in Web.Config file.

Textbox value will show other textbox information without clicking button

this code is working good. But i want to search data without click button. when i will write Employee name if it will exists in table it will show my information otherwise i will insert data. Please help me...
protected void btnSubmit_Click(object sender, EventArgs e){
var sqlQuery = "SELECT EmployeeID, Weight, Amount FROM Supplier where EmployeeName= '" + TextBox2.Text+ "'";
//Create Instance for DataSet
var DS = new DataSet();
//Create Instance for SqlConnection
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["inventoryConnectionString"].ConnectionString);
//Create Instance for SqlCommand
var cmd = new SqlCommand(sqlQuery, conn);
var DA = new SqlDataAdapter(cmd);
DS.Clear();
try{
DA.Fill(DS);
}
catch (Exception ex){}
foreach (DataRow row in DS.Tables[0].Rows){
txtBoxId.Text = row["EmployeeID"].ToString();
txtboxw.Text = row["Weight"].ToString();
txtboxam.Text = row["Amount"].ToString();
}
}
You could use TextChanged event handler and a parameterized query for sql injection protection. However, the code below be forwarned is costly because it has to access the Database from time to time.
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
String connString = ConfigurationManager.ConnectionStrings["inventoryConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
String strSQL = "SELECT EmployeeID, Weight, Amount FROM Supplier where EmployeeName=#EmployeeName";
using (SqlCommand cmd = new SqlCommand(strSQL, con))
{
cmd.Parameters.Add("#EmployeeName", SqlDbType.VarChar).Value = TextBox2.Text;
using (SqlDataAdapter DA = new SqlDataAdapter(cmd))
{
DA.SelectCommand = cmd;
try
{
DataSet DS = new DataSet();
DA.Fill(DS);
foreach (DataRow row in DS.Tables[0].Rows)
{
txtBoxId.Text = row["EmployeeID"].ToString();
txtboxw.Text = row["Weight"].ToString();
txtboxam.Text = row["Amount"].ToString();
}
}
catch (Exception ex)
{
}
}
}
}
}
However, you could probably just cached the whole table and then from there do the query instead of going to the database from time to time like:
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
var query = from myRow in myDataTable.AsEnumerable()
where r.Field<string>("EmployeeName")==TextBox2.Text
select new
{
EmployeeID = myRow.Field<int>("EmployeeID"),
Weight = contact.Field<int>("Weight"),
Amount = order.Field<double>("Amount")
};
foreach (var row in query)
{
txtBoxId.Text = row.Employee.ToString();
txtboxw.Text = row.Weight.ToString();
txtboxam.Text = row.Amount.ToString();
}
}
I've got a different approach. Assuming the contents of your Supplier table do not change frequently, I'd suggest caching the contents of that table on page load and then just reference that table when the text in that text box is changed.
private DataTable _suppliers;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sqlQuery = "SELECT EmployeeID, Weight, Amount, EmployeeName FROM Supplier";
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["inventoryConnectionString"].ConnectionString);
_suppliers = new DataTable();
var cmd = new SqlCommand(sqlQuery, conn);
conn.Open();
var SDA = new SqlDataAdapter(cmd);
SDA.Fill(_suppliers);
}
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
DataView DV = new DataView(_suppliers);
DV.RowFilter = string.Format("EmployeeName LIKE '%{0}%'", TextBox2.Text);
if (DV.Count == 1)
{
var row = DV[0];
txtBoxId.Text = row["EmployeeID"].ToString();
txtboxw.Text = row["Weight"].ToString();
txtboxam.Text = row["Amount"].ToString();
}
}
Additionally, you may want to look into using an updatepanel to handle the text changed event asynchronously instead of using the TextChanged event.

datagridview in webform c# show query in footer

I have two query's in C# running in a datagridview, one is to show all data. the other is set to display in the footer. The footer is showing, just not displaying my query.
query one (with footer)
protected void Button2_Click(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customer", cs);
cs.Open();
MySqlDataReader dgl = cmd.ExecuteReader();
dg.ShowFooter = true;
dg.DataSource = dgl;
dg.DataBind();
cs.Close();
}
**query two(footer query)**
protected void dg_DataBound(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", cs);
cs.Open();
String totalDonations = Convert.ToString(cmd.ExecuteScalar());
cs.Close();
dg.FooterRow.Cells[3].Text = totalDonations;
}
the datagrid shows query one works well, the footer even shows but it has not got any data.
Although you have it working, there are ways to improve it.
In the first method, using statement would manage the connection better:
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customer", con))
{
da.Fill(dt);
}
}
dg.ShowFooter = true;
dg.DataSource = dt;
dg.DataBind();
}
And the second method:
protected void dg_DataBound(object sender, EventArgs e)
{
String totalDonations = string.Empty;
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", con))
{
totalDonations = Convert.ToString(cmd.ExecuteScalar());
}
}
dg.FooterRow.Cells[3].Text = totalDonations;
}
Probably I would use GridView's RowDataBound to write into footer where I can can know the type of row:
protected void dg_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
String totalDonations = string.Empty;
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", con))
{
totalDonations = Convert.ToString(cmd.ExecuteScalar());
}
}
e.Row.Cells[3].Text = totalDonations;
}
}
EDIT : Here's the markup I have used to test:
<asp:GridView ID="dg" runat="server" AutoGenerateColumns="true" OnDataBound="dg_DataBound" ShowFooter="true">
</asp:GridView>
After hours of problems, I have solved it.
corrected code
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customer", cs);
MySqlCommand cmdtwo = new MySqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", cs);
cs.Open();
MySqlDataReader dgl = cmd.ExecuteReader();
dg.DataSource = dgl;
dg.ShowFooter = true;
dg.DataBind();
cs.Close();
cs.Open();
string totalDonations = Convert.ToString(cmdtwo.ExecuteScalar());
cs.Close();
dg.FooterRow.Cells[7].Text = "Total £";
dg.FooterRow.Cells[8].Text = totalDonations;
}
although I am sure there is a better way of doing this, if you know please feel free to edit.

C# Datagridview how to edit cell back to database

Good day to all. I have this code that populates the Datagridview. And I tried to edit it. But it seems I can't save any changes to database. Though I'm not getting any errors. Any help would be much appreciated. Thanks alot!
private void FrmViewCustomer_Load(object sender, EventArgs e)
{
string query = "SELECT CONCAT(firstname,', ',lastname) AS NAME, orderedgood AS OrderedGood FROM customer c;";
using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString))
{
conn.Open();
using (MySqlCommand command = new MySqlCommand(query, conn))
{
using (adapter = new MySqlDataAdapter(command))
{
dataGridView1.Rows.Clear();
dataGridView1.AllowUserToAddRows = false;
DataTable dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
this.adapter.Update(dt);
}
MyTable
id name
1 John
2 Carl
3 Sam
C# Code behind:
public partial class Form1 : Form
{
DataTable dt = null;
DataGridView dgv = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
using (MySqlConnection conn = new MySqlConnection("server=localhost;user=root;pwd=1234;database=test;"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select * from MyTable;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
conn.Close();
}
dgv = new DataGridView();
dgv.AllowUserToAddRows = false;
dgv.CellEndEdit += new DataGridViewCellEventHandler(dgv_CellEndEdit);
dgv.CellValidating += new DataGridViewCellValidatingEventHandler(dgv_CellValidating);
dgv.Dock = DockStyle.Fill;
dgv.DataSource = dt;
this.Controls.Add(dgv);
}
void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 0)
{
dgv.CancelEdit();
}
}
void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string id = dt.Rows[e.RowIndex]["id"] + "";
string col = dt.Columns[e.ColumnIndex].ColumnName;
string data = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value+"";
string sql = string.Format("UPDATE `MyTable` SET `{0}` = '{1}' WHERE ID = {2};", col, data, id);
using (MySqlConnection conn = new MySqlConnection("server=localhost;user=root;pwd=1234;database=test;"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}

Categories

Resources