Drawing several graphs from a listbox - c#

I made a code like below. I would like there to be as many charts as are selected in the ListBox. Now they are always drawn all of them. For example, I would like to select listBox1 is one graph and e.g. listBox1, listBox2, listBox3 are 3 graphs.
How to change it or what to add?
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add("value1");
listBox1.Items.Add("value2");
listBox1.Items.Add("value3");
listBox1.SelectionMode = SelectionMode.MultiSimple;
}
private void button1_Click_1(object sender, EventArgs e)
{
connect.Open();
string mysql = "SELECT value1, value2, value3, valuedate FROM mydata";
MySqlDataAdapter da = new MySqlDataAdapter(mysql, connect);
DataSet ds = new DataSet();
chart1.DataSource = ds.Tables[0];
chart1.Series["value1"].XValueMember = "valuedate";
chart1.Series["value1"].YValueMembers = "value1";
chart1.Series["value2"].XValueMember = "valuedate";
chart1.Series["value2"].YValueMembers = "value2";
chart1.Series["value3"].XValueMember = "valuedate";
chart1.Series["value3"].YValueMembers = "value3";
}

You should modify your query based on the items selected in the list view and then also similarly add the series.
The below code will give you an idea of how to approach it.
string query = "SELECT valuedate ";
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
string value = listView1.SelectedItems[i].Text;
query += ", " + value;
chart1.Series.Add(value);
chart1.Series[value].XValueMember = "valuedate";
chart1.Series[value].YValueMembers = value;
}
query += " FROM mydata";

Related

How to show numbers in row of dataGridView

Hello my dear friends,
I have a DataGridView and made a database connection to get a table.
If the user clicks on the button he gets the information in DataGridView object.
It looks like this:
private void button3_Click(object sender, EventArgs e)
{
dataGridView1.Refresh();
dataGridView1.Columns.Clear();
clsMSSQL.clsMSSQL mssql = new clsMSSQL.clsMSSQL(2);
string sql = ("select CCase.RefNo AS Az, EventTemplate.EventCode AS Vorgang from ikaros.CCase join ikaros.Event on CCase.ID = Event.CCaseID join ikaros.EventTemplate on Event.EventTemplateID = EventTemplate.ID where EventTemplate.EventCode='IRVB' and Event.EventDate ='2014-07-03' order by CCase.RefNo ASC");
mssql.Query(sql);
mssql.Fetch();
dataGridView1.ColumnCount = 2;
dataGridView1.Columns[0].Name = "Aktenzeichen";
dataGridView1.Columns[1].Name = "Vorgang";
while (!mssql.eof)
{
string[] arr_row = new string[2];
arr_row[0] = mssql.GetString("Az");
arr_row[1] = mssql.GetString("Vorgang");
dataGridView1.Rows.Add(arr_row);
mssql.Fetch();
}
dataGridView1.EndEdit();
dataGridView1.Refresh();
}
But I want to have numeric numbers on the left of the DataGridView.
So I tried:
row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
But "row" and the "HeaderCell" class gives a error.

display portion of textbox in listbox in C#

I have a textbox and a listbox in my c# forms application. What I want to do is that the user will enter the query in the textbox and I want to display the portion of that query into my listbox.
For example:
Here, I want to display "att1" and "att2" in my listbox named "Query Options"(i.e. listBox1). How can I do that?
This is the code I have written until now:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string x = (sender as Control).Text;
listBox1.BeginUpdate();
try
{
XmlDocument xdata = new XmlDocument();
xdata.Load("C:\\Ankush\\Visual Studio Project\\Query Info.xml");
XmlNodeList qlist = xdata.SelectNodes("information/QueryInfo/Query");
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (listBox1.Items[i].ToString().ToLower().Contains(textBox1.Text.ToLower()))
listBox1.SetSelected(i, true);
foreach (XmlNode node in qlist)
{
listBox1.DataSource = xdata;
listBox1.Items.Add(node.InnerText);
}
}
//listBox1.DataSource = xdata;
string cmdstr = #"select * from information_schema.columns where table_name = '" + comboBox1.SelectedItem + "'";
string conStr = #"Data Source=INPDDBA027\NGEP;Initial Catalog=Dev_Server;Integrated Security=True";
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmdstr, conStr);
sda.Fill(dt);
listBox2.DataSource = dt;
listBox2.DisplayMember = "Column_Name";
}
finally
{
listBox1.EndUpdate();
}
}
Please Help.

Delete the single selected row from a grid view at run time

I have a table having 2 columns viz ID and DETAILS.Data in a table is like
id=01 details="pritam=123 sourav=263" like this
i am working on a windows for application ..when the application will run the output comes what i am going to tell.. 1.in my application one combobox is there.when the application will run all the id will be bind in a combobox from the table. 2.when user will choose any id suddenly the details column data will be shown in a datagrid view in a splitted format like this.
NAME KEY
PRITAM 123
SOURAV 263
in this data grid view user can delete ant row by selecting the and click on the below delete button. insert any row by clickng the add new row button at the end ,modify any existing data and finally click on the update button and all the data are going to be stored in that data base like in previous format.. for that i have written the code in c# like this..
namespace windows_csharpp
{
public partial class Form5 : Form
{
SqlConnection cc = new SqlConnection("Integrated Security=true;database=EDIXfer");
SqlDataAdapter da;
DataTable dt;
public Form5()
{
InitializeComponent();
}
private void Form5_Load(object sender, EventArgs e)
{
string sql="select EDIScheduleID from ETAProcessSchedule";
da= new SqlDataAdapter(sql, cc);
dt = new System.Data.DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
comboBox1.Items.Add(dt.Rows[x][0].ToString());
}
}
ArrayList ls = new ArrayList();
int ss = 0;
int ss1 = 0;
int ssp = 1;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "select * from ETAProcessSchedule where EDIScheduleID='" + comboBox1.SelectedItem.ToString() + "'";
SqlDataAdapter adp = new SqlDataAdapter(sql, cc);
DataTable dt = new System.Data.DataTable();
adp.Fill(dt);
string stp = dt.Rows[0][21].ToString();
string[] stp1 = stp.Split(' ');
List<Class1> lst = new List<Class1>();
ls.Clear();
for (int x = 0; x < stp1.Length; x++)
{
ls.Add(stp1[x].ToString());
}
for (int x = 0; x < ls.Count; x++)
{
string ssttt = ls[x].ToString();
string[] sssp = ssttt.Split('=');
for (int x1 = 1; x1 < sssp.Length; x1++)
{
ss = 0;
ss1 = ssp;
Class1 cs = new Class1()
{
Value = sssp[ss], Key= sssp[x1].ToString()
};
lst.Add(cs);
}
}
dataGridView1.DataSource = lst;
}
private void Update_Click(object sender, EventArgs e)
{
string value = null;
string keys = null;
string query = null;
string str = null;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
value = dataGridView1.Rows[i].Cells[0].Value.ToString();
keys = dataGridView1.Rows[i].Cells[1].Value.ToString();
string ss = value + '=' + keys;
str += ss + ' ';
}
query = "update ETAProcessSchedule set ProcParameters='"+str+"' where EDIScheduleID='"+comboBox1.SelectedItem.ToString()+"'";
da = new SqlDataAdapter(query, cc);
dt = new DataTable();
da.Fill(dt);
MessageBox.Show("Data Updated In Database Successfully");
}
and one class file is also there ..
class Class1
{
public string Value { get; set; }
public string Key { get; set; }
}
kindly help me in delete the selected row ,add the new row and update the all data in database like in previous format..
I think you already have working approach. If I understand right you need only two functions:
- Load Schedule details in the DataGridView (one key-value pair per row)
- Save edited/added/deleted key-value pairs to the database
Be sure next properties of DataGridView set to true:
this.YourDataGridView.AllowUserToAddRows = true;
this.YourDataGridView.AllowUserToDeleteRows = true;
And of course columns must be editable
In the methods was used const variables which was created in your Form (Form1)
private const string DETAILSDELIMITER = ' ';
private const string NAMEKEYDELIMITER = '=';
Method for loading schedule details in the DataGridView
//Use SqlParameters in the query,
//if not your application vulnerable for sql injection
private void LoadScheduleDetails(string scheduleID)
{
//You working only with one column, do not use '*' in SELECT statement if not nessesary
string query = "SELECT EDIScheduleID, ProcParameters FROM ETAProcessSchedule WHERE EDIScheduleID = #ScheduleID";
DataTable details = new DataTable();
//Get data from database
using (SqlConnection yourConnection = new SqlConnection(_YourConnectionString))
{
using(SqlCommand detailsCommand = new SqlCommand(query, yourConnection))
{
//Adding parameter
SqlParameter id = new SqlParameter { ParameterName = "#ScheduleID", SqlDbType = SqlDbType.NVarChar, Value = scheduleID };
detailsCommand.Parameters.Add(id);
using (SqlDataAdapter yourAdapter = new SqlDataAdapter(detailsCommand ))
{
yourAdapter.Fill(details);
}
}
}
this.YourDataGridView.Rows.Clear();
if (details.Rows.Count > 0)
{
DataRow temp = details.Rows[0];
//get column by name.
string[] pairs = temp.Field<String>("ProcParameters").Split(Form1.DETAILSDELIMITER);
//Adding rows manually without DataSource
foreach(string pair in pairs)
{
this.YourDataGridView.Rows.Add(pair.Split(Form1.NAMEKEYDELIMITER));
}
}
}
Method for saving data
I think better if you create columns already in the designer
Then you can access columns by it's name without hardcoding indexes
private void SaveDetails(string scheduleID)
{
StringBuilder details = new StringBuilder();
foreach(DataGridViewRow dgvr in this.YourDataGridView.Rows)
{
string name = dgvr.Cells[this.dgvColumn_Name.Name].Value.ToString();
string key = dgvr.Cells[this.dgvColumn_Key.Name].Value.ToString();
//Here you can check if values are ok(not empty or something else)
//Create pair
details.Append(Form1.DETAILSDELIMITER);
details.Append(name);
details.Append(Form1.NAMEKEYDELIMITER);
details.Append(key);
}
//remove first space character
if (details.Length > 0)
details.Remove(0, 1);
//Save data to database
string query = "UPDATE ETAProcessSchedule SET ProcParameters=#Details WHERE EDIScheduleID=#ScheduleID";
using (SqlConnection yourConnection = new SqlConnection(_YourConnectionString))
{
using (SqlCommand saveCommand = new SqlCommand(query, yourConnection))
{
//Adding parameters
SqlParameter id = new SqlParameter { ParameterName = "#ScheduleID", SqlDbType = SqlDbType.NVarChar, Value = scheduleID };
SqlParameter procParams = new SqlParameter { ParameterName = "#Details", SqlDbType = SqlDbType.NVarChar, Value = details.ToString() };
saveCommand.Parameters.Add(id);
saveCommand.Parameters.Add(procParams);
saveCommand.ExecuteNonQuery();
MessageBox.Show("Data Updated In Database Successfully");
}
}
}
Then use LoadScheduleDetails in the comboBox1_SelectedIndexChanged eventhandler
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string scheduleID = comboBox1.SelectedItem.ToString();
if(String.IsNullOrEmpty(scheduleID) == false)
{
this.LoadScheduleDetails(scheduleID);
}
}
After data loaded, user can change it, add rows, delete rows
When user pressed "Update" button then use SaveDetails method,
where we collect data from all rows and update database with it
private void Update_Click(object sender, EventArgs e)
{
string scheduleID = comboBox1.SelectedItem.ToString();
if(String.IsNullOrEmpty(scheduleID) == false)
{
this.SaveDetails(scheduleID);
}
}
On your form load bind data:-
EDIT : -
private void Form5_Load(object sender, EventArgs e)
{
comboBox1.DataSource = loadddltable();
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
}
public DataTable loadddl()
{
OleDbDataReader obj = null;
DataTable dt = new DataTable();
try
{
obj_dbconnection.CommandText = "Select * from TableName";
obj = obj_dbconnection.ExecuteReader();
if (obj != null)
{
if (obj.HasRows)
{
dt.Load(obj);
}
}
}
catch (Exception)
{
}
finally
{
if (obj != null)
{
obj.Close();
obj_dbconnection.Close();
}
}
return dt;
}
/*Code for Execute Reader*/
public OleDbDataReader ExecuteReader()
{
OleDbDataReader dr = null;
try
{
Open();
dr = cmd.ExecuteReader();
}
catch(Exception)
{ }
return dr;
}
/*Code for binding grid data*/
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource= getDataForSelectedId(comboBox1.SelectedValue);
}
And then insert,edit,delete buttons as template fields to dataGridView and use dataGridView1_CellClick event to insert edit delete

Filtering combo box items using text search in C# windows form

I'm Trying to filter a combo box using its text property in all characters of Items not only Beginning of them. I'm trying below code in TextChanged event of my combo box. but unfortunately combo box resets after entering any key:
private void cmbCompany_TextChanged(object sender, EventArgs e)
{
string QueryCompany = string.Format("select id,title from acc.dl where title LIKE '%" + cmbCompany.Text + "%' union select null , null order by title");
SqlDataAdapter DA1 = new SqlDataAdapter(QueryCompany, con);
DataTable DT1 = new DataTable();
DA1.Fill(DT1);
cmbCompany.DisplayMember = "Title";
cmbCompany.ValueMember = "id";
cmbCompany.DataSource = DT1;
}
connection string "con" is defined and opened.
thanks for your helps.
Below part of code which works for me where searching part works not only at the begining but also in the middle. I paste also additional part responsible for move focus to the next control on the form after you hit enter button.
Initialization part:
public Form1()
{
InitializeComponent();
cmbItems = new List<ComboBoxItem>();
InitializeComboBox();
}
private void InitializeComboBox()
{
Random rand = new Random();
for (int i = 0; i <= 1500; i++)
{
int counter = rand.Next(1, 105000);
cmbItems.Add(new ComboBoxItem("randomNumber" + counter, "ID_" + counter));
}
comboBox1.DataSource = cmbItems;
}
Filtering part:
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
if (comboBox1.Text == string.Empty)
{
comboBox1.DataSource = cmbItems; // cmbItems is a List of ComboBoxItem with some random numbers
comboBox1.SelectedIndex = -1;
}
else
{
string tempStr = comboBox1.Text;
IEnumerable<ComboBoxItem> data = (from m in cmbItems where m.Label.ToLower().Contains(tempStr.ToLower()) select m);
comboBox1.DataSource = null;
comboBox1.Items.Clear();
foreach (var temp in data)
{
comboBox1.Items.Add(temp);
}
comboBox1.DroppedDown = true;
Cursor.Current = Cursors.Default;
comboBox1.SelectedIndex = -1;
comboBox1.Text = tempStr;
comboBox1.Select(comboBox1.Text.Length, 0);
}
}
Moving focus part:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\r') return;
if (this.ActiveControl != null)
{
this.SelectNextControl(this.ActiveControl, true, true, true, true);
}
e.Handled = true; // Mark the event as handled
}
I hope that helps someone.
you can add a textbox to your form and use it's text to filter :
string QueryCompany =
string.Format(
"select id,title from acc.dl where dltype in (2,4) union select null , null order by title");
SqlDataAdapter DA1 = new SqlDataAdapter(QueryCompany, con);
con.Open();
DataTable DT1 = new DataTable();
DA1.Fill(DT1);
con.Close();
DataView dv1 = new DataView(DT1);
dv1.RowFilter = "Title like '%" + txtCompany.Text + "%' or Title is null";
cmbCompany.DisplayMember = "Title";
cmbCompany.ValueMember = "id";
cmbCompany.DataSource = dv1;
and in selected index changed event :
txtCompany.Text = cmbCompany.Text;

update Cascading combobox problem C#

i have a simple question
i have a form which contain two related combo boxes but i have problem in updating the second dropdown content
this is the code
private void DiaryForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'expensesDataSet.Item' table. You can move, or remove it, as needed.
// this.itemTableAdapter.Fill(this.expensesDataSet.Item);
using (OleDbConnection con = dbconn.dbconnection())
{
ds1 = new ExpensesDataSet();
string sql = "SELECT * From DiaryView";
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
da.Fill(ds1, "DiaryView");
NavigateRecords();
MaxRows = ds1.Tables["DiaryView"].Rows.Count;
//fill category combobox
string sqlcat = "SELECT * From Category";
catda = new System.Data.OleDb.OleDbDataAdapter(sqlcat, con);
catda.Fill(ds1, "Category");
catda.Update(ds1, "Category");
comboBox2.DataSource=ds1.Tables["Category"];
comboBox2.DisplayMember = "cat_name";
comboBox2.ValueMember="cat_id";
//comboBox1.Enabled = false;
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
using (OleDbConnection con = dbconn.dbconnection())
{
if (comboBox2.Items.Count > 0)
{
{
string cat = comboBox2.SelectedValue.ToString();
comboBox1.Enabled = true;
int catid = int.Parse(comboBox2.SelectedValue.ToString());
string sqlitem = "SELECT * From Item where cat_id = " + catid;
catda = new System.Data.OleDb.OleDbDataAdapter(sqlitem, con);
this.itemBindingSource.EndEdit();
catda.Fill(ds1, "Item");
catda.Update(ds1, "Item");
comboBox1.DataSource = ds1.Tables["Item"];
comboBox1.DisplayMember = "item_name";
comboBox1.ValueMember = "item_id";
}
}
}
}
there is two tables:
category(cat_id,cat_name)
item(item_id,item_name,cat_id)
what can i do??
plz help :)
If you want to clear the combobox, just do:
combobox1.Items.Clear();
It's as easy as that.

Categories