I am trying to display ajax bar chart in my web page. But it is only displaying one value .
My db contains 3 columns(name, credit, debit) I want to display the credit debit values in chart. But the chart is only displaying one value. How can I modify the given below coding. Thank you.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select Name from aTable";
DataTable dt = GetData(query);
ddlCountries.DataSource = dt;
ddlCountries.DataTextField = "Name";
ddlCountries.DataValueField = "Name";
ddlCountries.DataBind();
ddlCountries.Items.Insert(0, new ListItem("Select", ""));
}
}
private DataTable GetData(string query, SqlParameter[] prms = null)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
if (prms != null)
cmd.Parameters.AddRange(prms);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
string query = "select Name, Debit, Credit From aTable where Name=#Name";
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#name", SqlDbType.NVarChar);
prms[0].Value = ddlCountries.SelectedItem.Value.ToString();
DataTable dt = GetData(query, prms);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = y });
BarChart1.CategoriesAxis = string.Join(",", x);
BarChart1.ChartTitle = string.Format("{0} -RunTimeReportChart", ddlCountries.SelectedItem.Value);
if (x.Length > 3)
{
BarChart1.ChartWidth = (x.Length * 100).ToString();
}
BarChart1.Visible = ddlCountries.SelectedItem.Value != "";
}
Data Base:
Actual Output:
The given below chart is only displaying the name and debit value. I want to display the credit value also. Please help me.
Something Like :
decimal[] z = new decimal[dt.Rows.Count];
z[i] = Convert.ToInt32(dt.Rows[i][2]);
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = z });
Related
Im currently using this method to bind my treeview, After i expand the treeview and click the node, it will redirect to another page, and then the treeview will be refresh to default, which means showing the treeview before expanding.. so i need to save the treeview state in order to remain the treeview state. i had tried the below method but it's not working, anyone can help..
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadTransactionMenu();
if (Session["ExpandedNodes"] != null)
((List<string>)Session["ExpandedNodes"]).ForEach(a => TreeView1.FindNode(a).Expanded = true);
}
}
private void LoadTransactionMenu()
{
//TRANSACTION MENU
string SubModuleID, SubModuleNM, DocModuleID, DocModuleName, MenuTransID, MenuTransName;
SqlConnection con = new SqlConnection(ConString);
string CmdString = "SELECT SUBMODULEID, SUBMODULENM, URLNAME FROM SUBMODULE";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
TreeNode node1 = new TreeNode();
node1.Text = "TRANSACTION MENU";
TreeView1.Nodes.Add(node1);
for (int i = 0; i < dt.Rows.Count; i++)
{
SubModuleID = dt.Rows[i]["SUBMODULEID"].ToString();
SubModuleNM = dt.Rows[i]["SUBMODULENM"].ToString();
TreeNode SubModuleNode = new TreeNode(SubModuleNM, SubModuleID);
SubModuleNode.NavigateUrl = dt.Rows[i]["URLNAME"].ToString();
node1.ChildNodes.Add(SubModuleNode);
CmdString = "SELECT DDID, DOCNAME, DDADDRESS FROM DOCMODULE WHERE SUBMODULEID=#SUBMODULEID";
cmd = new SqlCommand(CmdString, con);
cmd.Parameters.AddWithValue("#SUBMODULEID", SubModuleID);
sda = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
sda.Fill(dt2);
for (int j = 0; j < dt2.Rows.Count; j++)
{
DocModuleID = dt2.Rows[j]["DDID"].ToString();
DocModuleName = dt2.Rows[j]["DOCNAME"].ToString();
TreeNode DocModuleNode = new TreeNode(DocModuleName, DocModuleID);
DocModuleNode.NavigateUrl = dt2.Rows[j]["DDADDRESS"].ToString();
SubModuleNode.ChildNodes.Add(DocModuleNode);
CmdString = "SELECT DID, DNAME, DADDRESS FROM MENUTRANSACTION WHERE DDID=#DDID AND UID= '" + Session["UserID"] + "'";
cmd = new SqlCommand(CmdString, con);
cmd.Parameters.AddWithValue("#DDID", DocModuleID);
sda = new SqlDataAdapter(cmd);
DataTable dt3 = new DataTable();
sda.Fill(dt3);
for (int k = 0; k < dt3.Rows.Count; k++)
{
MenuTransID = dt3.Rows[k]["DID"].ToString();
MenuTransName = dt3.Rows[k]["DNAME"].ToString();
TreeNode MenuTransNode = new TreeNode(MenuTransName, MenuTransID);
MenuTransNode.NavigateUrl = dt3.Rows[k]["DADDRESS"].ToString();
DocModuleNode.ChildNodes.Add(MenuTransNode);
}
if (DocModuleNode.ChildNodes.Count == 0)
{
SubModuleNode.ChildNodes.Remove(DocModuleNode);
}
}
if (SubModuleNode.ChildNodes.Count == 0)
{
node1.ChildNodes.Remove(SubModuleNode);
}
}
}
public void GetExpandedStatus(TreeNode node, List<string> ExpandedNodes)
{
//check if node is expanded
if (node.Expanded.GetValueOrDefault(false))
ExpandedNodes.Add(node.ValuePath);
node.ChildNodes.Cast<TreeNode>().ToList().ForEach(a => GetExpandedStatus(a, ExpandedNodes));
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
List<string> expandedNodes = new List<string>();
//get all expanded nodes
TreeView1.Nodes.Cast<TreeNode>().ToList().ForEach(a => GetExpandedStatus(a, expandedNodes));
//collapse all to reset the treeview
TreeView1.CollapseAll();
//save expanded node value paths
Session["ExpandedNodes"] = expandedNodes;
}
I have a form with two combo boxes which both have a list from a database. In this case one is a list of countries and based on the value selected there, the second list is updated to show only the cities that belong to the selected country. After that, the values are combined and stored in my program like "city, country".
When I open my form I retrieve that information and separate the values back to just country and city. All working. The trouble I have now is that the comboboxes should display the retrieved values if the correspond to a value found in the list/database. I tried as shown below, but that is not working. I guess it has something to do with adding a new row to the database to show "--Select Country--" and "--Select City--".
I hope you can point me in the right direction. Thank you all in advance for your replies.
comboBoxCountry.SelectedValue = comboBoxCountry.FindString(country);
comboBoxCity.SelectedValue = comboBoxCity.FindString(city);
public partial class FormPropertyEditor : Form
{
//Connect to local database.mdf
SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
#"C:\Users\gleonvanlier\AppData\Roaming\Autodesk\ApplicationPlugins\MHS Property Editor\Database.mdf;" +
"Integrated Security=True;Connect Timeout=30;User Instance=False;");
DataRow dr;
public FormPropertyEditor()
{
InitializeComponent();
ReadProperties();
refreshdata();
}
public void refreshdata()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TblCountries Order by CountryName", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, "--Select Country--" };
dt.Rows.InsertAt(dr, 0);
comboBoxCountry.ValueMember = "CountryID";
comboBoxCountry.DisplayMember = "CountryName";
comboBoxCountry.DataSource = dt;
comboBoxCountry.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBoxCountry.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void comboBoxCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxCountry.SelectedValue.ToString() != null)
{
int CountryID = Convert.ToInt32(comboBoxCountry.SelectedValue.ToString());
refreshstate(CountryID);
}
}
public void refreshstate(int CountryID)
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TblCities where CountryID= #CountryID Order by CityName", con);
cmd.Parameters.AddWithValue("CountryID", CountryID);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, 0, "--Select City--" };
dt.Rows.InsertAt(dr, 0);
comboBoxCity.ValueMember = "CityID";
comboBoxCity.DisplayMember = "CityName";
comboBoxCity.DataSource = dt;
comboBoxCity.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBoxCity.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void ReadProperties()
{
string progId = "Inventor.Application";
Type inventorApplicationType = Type.GetTypeFromProgID(progId);
Inventor.Application invApp = (Inventor.Application)Marshal.GetActiveObject(progId);
//Get the active document in Inventor
Document oDoc = (Document)invApp.ActiveDocument;
ReadProperties readProperties = new ReadProperties();
//Read Customer
string txtCustomer = readProperties.ReadCustomProperty("Customer", oDoc).ToString();
this.textBoxCustomer.Text = txtCustomer;
//Read Location
string txtLocation = readProperties.ReadCustomProperty("Location", oDoc).ToString();
try
{
string[] location = txtLocation.Split(',', ' ');
string city = location[0];
string country = location[1];
comboBoxCountry.SelectedValue = comboBoxCountry.FindString(country);
comboBoxCity.SelectedValue = comboBoxCity.FindString(city);
}
catch (Exception e)
{
string city = string.Empty;
string country = string.Empty;
}
}
This solved it:
comboBoxCountry.SelectedIndex = comboBoxCountry.FindStringExact(country);
comboBoxCity.SelectedIndex = comboBoxCity.FindStringExact(city);
I have 3 listboxes.The listbox fetches two values by code-datatextfield and datavaluefield. 1st listbox transfers the datatextfield items from 1st listbox to 2nd listbox.i want to transfer the datavaluefield of selected 1st listbox items to 3rd listbox.
if (ListBox3.SelectedIndex >= 0
{
for (int i = 0; i < ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox3.Items[i]))
{
arraylist1.Add(ListBox3.Items[i]);
Session["value"] = ListBox3.Items[i];
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i]));
}
ListBox3.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
}
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where paramtext='" + Session["value"] + "'", con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "param";
//ListBox3.DataValueField = "param";
ListBox1.DataBind();
}
for listbox 3
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where pname='" + this.DropDownList1.SelectedValue + "'" ,con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox3.DataSource = ds.Tables[0];
ListBox3.DataTextField = "paramtext";
ListBox3.DataValueField = "param";
ListBox3.DataBind();
}
}
But i want to display the datavaluefield of the items that are selected from listbox3 to listbox1
Since you want to show DataTextField value and DataValueField value from one listbox into 2 different listbox. I suggest you to use a different approach. This will also reduce usage of 2nd database call.
Try following:-
if (ListBox3.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox3.Items[i]))
{
arraylist1.Add(ListBox3.Items[i]);
//Session["value"] = ListBox3.Items[i]; no need of this
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (ListBox2.Items.FindByText(((ListItem)arraylist1[i]).Text)==null)
{
//since you already have text and value field values in arrayList. Use them
ListBox2.Items.Add(new ListItem(((ListItem)arraylist1[i]).Text));
}
if (ListBox1.Items.FindByText(((ListItem)arraylist1[i]).Text)==null)
{
ListBox1.Items.Add(new ListItem((ListItem)arraylist1[i]).Value));
}
ListBox3.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
}
/* This database call can be removed
SqlConnection con = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("select * from IT_1_BOILER_DESK_1_PARAMETERS where paramtext='" + Session["value"] + "'", con);
SqlDataAdapter dataAadpter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
dataAadpter.Fill(ds);
if (ds != null)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "param";
//ListBox3.DataValueField = "param";
ListBox1.DataBind();
}*/
I have a DataTable and I want to select multiple columns on the DataTable that matches the input in the textbox. The code below only selects 1 column.
var result = from data in mDataTable.AsEnumerable ()
where data.Field<string>("Code") == txtCode.Text
select data.Field<string> ("Description");
foreach (var res in result) {
txtxDescription.Text = res.ToString ();
}
How can I select 2 or more columns on DataTable using LINQ?
why not select full rows (DataRow object) and then take all necessary values from them?
var rows = mDataTable.AsEnumerable()
.Where(data => data.Field<string>("Code") == txtCode.Text);
foreach(DataRow r in rows)
{
txtxDescription.Text = r.Field<string>("Description");
}
another option is to project data to anonymous objects:
var result = from data in mDataTable.AsEnumerable ()
where data.Field<string>("Code") == txtCode.Text
select new
{
Description = data.Field<string> ("Description"),
Code = data.Field<string> ("Code")
};
foreach (var res in result)
{
// last value always replace `txtxDescription.Text` ??
txtxDescription.Text = res.Description;
txtxCode.Text = res.Code;
}
public void GridviewBinding()
{
DataSet ds = new DataSet();
string constr = ConfigurationManager.ConnectionStrings["SQLMSDB"].ConnectionString;
string sql = "select * from tbl_users";
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
gridviewcontrol.DataSource = ds;
gridviewcontrol.DataBind();
ViewState["GridViewBindingData"] = ds.Tables[0];
}
}
}
}
protected void btn_searching_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txt_search.Text.Trim().ToString()) || !String.IsNullOrWhiteSpace(txt_search.Text.Trim().ToString()))
{
DataTable dt = (DataTable)ViewState["GridViewBindingData"];
var dataRow = dt.AsEnumerable().Where(x => x.Field<dynamic>("UserName") == txt_search.Text);
DataTable dt2 = dataRow.CopyToDataTable<DataRow>();
gridviewcontrol.DataSource = dt2;
gridviewcontrol.DataBind();
}
else
{
GridviewBinding();
}
}
The first one is function with query to access information about driver from table tblDDDDriver by using VehicleNumber which is one of the field or column name in tblDDDDriver.
The second one is what i coded to access that function.
Now when i click the button i shows the error Invalid object name 'tblDDDDriver'
public DataTable GetDriverByVehicalNumber(string VehicleNumber)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=tprojectDB;");
string sql = "select *from tblDDDDriver where VehicleNumber=#VehicleNumber";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#VehicleNumber", VehicleNumber);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
private void button6_Click(object sender, EventArgs e)
{
DataTable dt = dc.GetDriverByVehicalNumber(txtvehicleno.Text);
if (dt.Rows.Count > 0)
{
txtlicenseno.Text = dt.Rows[0]["LicenseNumber"].ToString();
txtlicensecategory.Text = dt.Rows[0]["LicenseCategory"].ToString();
txtissuedate.Text = dt.Rows[0]["IssueDate"].ToString();
txtrenewdate.Text = dt.Rows[0]["RenewDate"].ToString();
txtfullname.Text = dt.Rows[0]["FullName"].ToString();
txtdob.Text = dt.Rows[0]["DOB"].ToString();
txtaddress.Text = dt.Rows[0]["Address"].ToString();
string gender = dt.Rows[0]["Gender"].ToString();
if (gender == "Male")
{
txtgender.Text = " MALE";
}
else
{
txtgender.Text = "FEMALE";
}
txtvehicleno.Text = dt.Rows[0]["VehicleNumber"].ToString();
txthealthstaus.Text = dt.Rows[0]["HealthStatus"].ToString();
txtdrivertype.Text = dt.Rows[0]["DriverType"].ToString();
Image img;
byte[] bytimg = (byte[])dt.Rows[0]["Image"];
//convert byte of imagedate to Image format
using (MemoryStream ms = new MemoryStream(bytimg, 0, bytimg.Length))
{
ms.Write(bytimg, 0, bytimg.Length);
img = Image.FromStream(ms, true);
pictureBox1.Image = img;
}
}
DataTable dd = dc.GetMaxDeathNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dd.Rows.Count > 0)
{
txtdeathaccidentno.Text = dd.Rows[0]["DeathNumber"].ToString();
}
DataTable dM = dc.GetMaxMajorNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dM.Rows.Count > 0)
{
txtmajoraccidentno.Text = dM.Rows[0]["MajorNumber"].ToString();
}
DataTable dm = dc.GetMaxMinorNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dm.Rows.Count > 0)
{
txtminoraccidentno.Text = dm.Rows[0]["MinorNumber"].ToString();
}
DataTable dtrb = dc.GetTrafficRuleBroken(Convert.ToDecimal(txtlicensenumber.Text));
{
dataGridView1.DataSource = dtrb;
}
}