If else statement between two combobox using c# - c#

I implemented two Combobox in my coding. 1st combobox contain the city name and the 2nd combobox contain the POI of that city. Now I want to implement if else statement between this two combobox. Suppose if I select 1st combobox, Button will enable only for 1st one, then if I select 2nd Combobox then Button will work for 2nd one. I do not know how to do it. My code is like this
public void Download_Click(object sender, EventArgs e)
{
// if combox1 select
// all function will work for combobox 1
//else if combobox2 select
//combobbox1 disabled and all function will work for combobx2
}
Initially I created class to set the value of combobox1 like this
class PlaceList
{
public static ComboBox Combo_list = new ComboBox();
public static DataGridView dataTable = new DataGridView();
public static void List()
{
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "POI_List");
System.IO.Directory.CreateDirectory(folderName);
string SavedfileName = "POI_list.json";
var Saving_path = Path.Combine(folderName, SavedfileName);
string fileName = "Zensus_Gemeinden_org.xlsx";
var path = Path.Combine(startPath, fileName);
String name = "Gemeinden_31.12.2011_Vergleich";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
path + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select [3] as City,[4] as Population, * From [" + name + "$D7:E11300] Where [4] > 10000", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataTable.DataSource = data;
for (int i = 0; i < data.Rows.Count; i++)
{
Combo_list.Items.Add(data.Rows[i]["City"]);
}
string Place_Json = "Place_List:" + JsonConvert.SerializeObject(data, Formatting.Indented);
File.WriteAllText(Saving_path, Place_Json);
}
}
}
Then in Form1.cs I created
Dictionary<string, List<string>> poi = new Dictionary<string, List<string>>();
private void LoadKeys()
{
foreach (string line in File.ReadLines("TextFile1.txt"))
{
string[] parts = line.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
poi.Add(parts[0], new List<string>());
poi[parts[0]] = new List<string>(parts.Skip(1));
}
}
void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem != null)
{
string txt = comboBox1.SelectedItem.ToString();
if (poi.ContainsKey(txt))
{
List<string> points = poi[txt];
comboBox2.Items.Clear();
comboBox2.Items.AddRange(points.ToArray());
}
}
}
That means combobox2 is dependent of combobox1. It will give the places name accoerding to the combobox1
then finally in form1.cs button 1 I am trying to do this somethis like this
public Form1()
{
InitializeComponent();
PlaceList.Combo_list = comboBox1;
PlaceList.List();
LoadKeys();
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != 0)
{
ShortText.txt1 = richTextBox1;
ShortText.shortText(comboBox1.Text);
}
else if (comboBox2.SelectedIndex != 0)
{
ShortText.txt1 = richTextBox1;
ShortText.shortText(comboBox2.Text);
}
else
{
MessageBox.Show("Error");
}

Check the selected index of each combobox for the default value. The one that isn't the default value is the one you use. For example, if the default is index 0:
if(combo1.SelectedIndex != 0){
//do something
}
else if(combo2.SelectedIndex != 0) {
//do something else
}
else {
// Error: You need to select something!
}

Related

Increase a variable in a loop and for each increment, apply for each new thread

How to increase a variable every time I create a new Thread and store that value? I want to do mysqlbackup in each thread for different databases, and I will get the curBytes/totalBytes completed on Class1.cs. I want to update that value into datagridview.Row[iterate].Cell[2] simultaneously between threads where iterate corresponds with value 0 for first thread, 1 for second thread and so on.
I have tried using Interlocked.Increment and lock() but they seem not to work. I don't want to use BackgroundWorker.
This is the code that I haven't done anything to change datagridIterate (the value that iterate through datagridview Rows)
Form.cs:
private void button1_Click(object sender, EventArgs e)
{
restoreUI();
}
public void restoreUI()
{
mysqlUtils msu = new mysqlUtils();
foreach(DataGridViewRow row in dataGridView1.Rows)
{
Thread t = new Thread(() =>
{
msu.Restore(row.Cells[1].Value?.ToString(), server.Text, username.Text,
pwd.Text, row.Cells[0].Value?.ToString());
}
t.Start();
}
}
Class1.cs:
namespace Utils
{
public class mysqlUtils
{
public int total;
public int cur;
public void Restore(string filename, string server, string user,
string password, string db)
{
string constring = "server=" + server + ";user=" + user +
";pwd=" + password + ";database=" + db + ";";
string file = "C:\\Users\\SQL FILES\\" + filename;
using (MySqlConnection conn = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = conn;
conn.Open();
mb.ImportInfo.IntervalForProgressReport = 50;
mb.ImportProgressChanged += updateProgress;
mb.ImportFromFile(file);
conn.Close();
}
}
}
}
}
public void updateProgress(object sender, ImportProgressArgs e)
{
total = (int)e.TotalBytes;
cur = (int)e.CurrentBytes;
Form4 form4 = (Form4)Application.OpenForms[0];
form4.updateProgressValue(total, cur);
}
}
How should I manage to change datagridIterate that will have value i for first thread, i+1 for the next thread and so on? I would highly appreciate if you have any support.
Here's a big hint for your code that might help you to understand what you need.
Try this:
public class Form4 : Form
{
private DataGridView dataGridView1 = new DataGridView();
private TextBox server = new TextBox();
private TextBox username = new TextBox();
private TextBox pwd = new TextBox();
private void button1_Click(object sender, EventArgs e)
{
RestoreUI();
}
public void RestoreUI()
{
MySqlUtils msu = new MySqlUtils();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string filename = row.Cells[1].Value?.ToString();
string s = server.Text;
string user = username.Text;
string password = pwd.Text;
string db = row.Cells[0].Value?.ToString();
Thread t = new Thread(() => msu.Restore(filename, s, user, password, db, UpdateProgress));
t.Start();
}
}
public void UpdateProgress(object sender, ImportProgressArgs e)
{
this.Invoke((Action)(() =>
{
/* add your code here to update the UI */
}));
}
}
And your MySqlUtils class.
public class MySqlUtils
{
public void Restore(string filename, string server, string user, string password, string db, ImportProgressChange updateProgress)
{
string constring = "server=" + server + ";user=" + user + ";pwd=" + password + ";database=" + db + ";";
string file = "C:\\Users\\SQL FILES\\" + filename;
using (MySqlConnection conn = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = conn;
conn.Open();
mb.ImportInfo.IntervalForProgressReport = 50;
mb.ImportProgressChanged += updateProgress;
mb.ImportFromFile(file);
conn.Close();
}
}
}
}
}
NB: I've changed the naming conventions to standard C#.

Load image from datagridview c#

Im trying to fill a DataGridView with the value coming from my database. There is one column that has a value of a BLOB or image. Now when I'm loading it to the DataGridView it shows an error: Parameter is not valid. Can someone help me about this?
Triggering the method
private void Form1_Load(object sender, EventArgs e)
{
//load company to datagrid
string company = "SELECT * from tbl_payroll_company";
payroll.FillDataGrid(company, payroll_company_datagrid);
}
Method for filling my datagrid
public void FillDataGrid(string query,DataGridView gridview)
{
dbcon.Initialize();
if (dbcon.OpenCon() == true)
{
dt = new DataTable();
adapter = new MySqlDataAdapter(query, dbcon.con);
adapter.Fill(dt);
gridview.DataSource = dt;
dbcon.con.Close();
}
}
Here's how i saved it
private void btnCompanyUpload_Click(object sender, EventArgs e)
{
OpenFileDialog CompanyFileDialog = new OpenFileDialog();
if(CompanyFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
Image logo = Bitmap.FromFile(CompanyFileDialog.FileName);
payroll_company_logo.Image = logo;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void btnCompanySave_Click(object sender, EventArgs e)
{
if(dbcon.OpenCon() == true)
{
MemoryStream stream = new MemoryStream();
if (payroll_company_logo.Image != null)
{
payroll_company_logo.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
byte[] logo = stream.ToArray();
string[] column_name = {"payroll_company_logo"};
string table = "tbl_payroll_company";
string[] column_value = {logo.ToString()};
dbcon.Insert(table,column_name,column_value);
}
}
public void Insert(string table,string[] columns,string[] values)
{
this.Initialize();
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO " + table + "(" + string.Join(",", columns) + ") VALUES('" + string.Join("','", values) + "')", con);
int check = cmd.ExecuteNonQuery();
con.Close();
}
ERROR

How to call Public method from Form1.cs with Combobox item

In my code in POI class I want to implement some method, at first it will take data from .xls file.Then it will show city and population name in the datagridview table.Now from datagridview table it will take only the city name which will show in the 1st Combobox. Then if someone click on the 1st combobox item it will show some places in that city on the second combobox. However I wrote the code. Now I got puzzled how to call it from Form1.cs and how it will work, because at this moment it is not working at all.
My code for POI class is
public class POI
{
Form f;
public static ComboBox Combo_list1 = new ComboBox();
public static ComboBox Combo_list2 = new ComboBox();
public static DataGridView dataTable = new DataGridView();
Dictionary<string, List<string>> poi = new Dictionary<string, List<string>>();
public void List(Form f)
{
f = new Form();
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "POI_List");
System.IO.Directory.CreateDirectory(folderName);
string SavedfileName = "POI_list.json";
var Saving_path = Path.Combine(folderName, SavedfileName);
string fileName = "Zensus_Gemeinden_org.xlsx";
var path = Path.Combine(startPath, fileName);
String name = "Gemeinden_31.12.2011_Vergleich";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
path + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select [3] as City,[4] as Population, * From [" + name + "$D7:E11300] Where [4] > 10000", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataTable.DataSource = data;
for (int i = 0; i < data.Rows.Count; i++)
{
Combo_list1.Items.Add(data.Rows[i]["City"]);
}
string Place_Json = "Place_List:" + JsonConvert.SerializeObject(data, Formatting.Indented);
File.WriteAllText(Saving_path, Place_Json);
foreach(string line in File.ReadLines("POIList.txt"))
{
string[] parts = line.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
poi.Add(parts[0], new List<string>());
poi[parts[0]] = new List<string>(parts.Skip(1));
}
}
public void Combo_list_SelectedIndexChanged(object sender, EventArgs e)
{
if (Combo_list1.SelectedItem != null)
{
string txt = Combo_list1.SelectedItem.ToString();
if (poi.ContainsKey(txt))
{
List<string> points = poi[txt];
Combo_list2.Items.Clear();
Combo_list2.Items.AddRange(points.ToArray());
}
}
}
}
I want to call both method in my form1.cs class. but it is not working. Form1.cs look like this-
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
POI.Combo_list1 = comboBox1;
POI.dataTable = dataGridView1;
//POI.List();
//POI
}
private void button1_Click(object sender, EventArgs e)
{
}
}
sorry for such a long code.Answer is greatly appreciate.
in the way your code is currently written you need to instantiate a POI object in order to call those methods. you could either do that or make those methods static.
POI.List() of course will not work beacuse POI isn't an static class. Instead you should initialize a POI class object
POI instaceObj = new POI();
instanceObj.List();
Also I think that you should improve your code.
Hope this help.

How to delete a row from gridview on button click after the row's checkbox is selected

I have a DataGridView created in C# windows forms and checkboxColumn added to it. The DataGridView is populated with other columns like Sno, AccountNo, Name, Salary (Sno is identitycolumn and primarykey).
I want to delete a row (using stored procedure) by selecting the checkbox and on button click which is out side DataGridView. Error at "FindControl".
Stored Procedure:
Create Procedure uspDeleteSelectedRow
As
Delete from EmpDetails where Sno=Sno
Go
private void btnDelete_Click(object sender, EventArgs e)
{
//Create String Collection to store IDs of
//records to be deleted
StringCollection idCollection = new StringCollection();
string strID = string.Empty;
//Loop through GridView rows to find checked rows
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)dataGridView1.Rows[i].
Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = dataGridView1.Rows[i].Cells[1].ToString();
idCollection.Add(strID);
}
}
}
if (idCollection.Count > 0)
{
//Call the method to Delete records
DeleteMultipleRecords(idCollection);
// rebind the GridView
dataGridView1.DataBind();
}
else
{
lblMessage.Text = "Please select any row to delete";
}
}
private void DeleteMultipleRecords(StringCollection idCollection)
{
//Create sql Connection and Sql Command
SqlConnection con = new SqlConnection(Helper.ConnectionString);
SqlCommand cmd = new SqlCommand();
string IDs = "";
foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string test = IDs.Substring
(0, IDs.LastIndexOf(","));
string sql = "Delete from EmpDetails" + " WHERE ID in (" + test + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}
Let say this is your stored procedure:
ALTER PROCEDURE [dbo].[sp_ToDeleteEmpDetails] #Sno int
/*
(
#parameter1 int = 5,
#parameter2 datatype OUTPUT
)
*/
AS
DELETE FROM EmpDetails
WHERE Sno = Sno
RETURN
You don't need a StringCollection to delete or call the stored procedure.
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in dataGridView1.Rows)
{
bool IsBool = false;
if (bool.TryParse(item.Cells[1].EditedFormattedValue.ToString(), out IsBool)) //<--Where: The ColumnIndex of the DataGridViewCheckBoxCell
{
using (SqlConnection con = new SqlConnection(Helper.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("sp_ToDeleteEmpDetails", con))
{
try {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#sno", SqlDbType.Int).Value = item.Cells[0].EditedFormattedValue.ToString(); //<--Where: The ColumnIndex of the Primary key from your DataGridView
dataGridView1.Rows.RemoveAt(item.Cells[0].RowIndex);
con.Open();
cmd.ExecuteNonQuery();
} catch (Exception) {
throw;
}
finally
{
con.Close();
}
}
}
}
}
}
Please let me know if you have some encountered problem from my given answer.
Try this solution. In my code I have class and pass a list of it to gridview as my datasource.
//Class
public class User
{
public bool Selected { get; set; }
public string UserName { get; set; }
}
//Create a list and bind to the data grid view
private void Form1_Load(object sender, EventArgs e)
{
var users = new List<User> { new User { UserName = "Jobert", Selected = false }, new User { UserName = "John", Selected = true }, new User { UserName = "Leah", Selected = true }, new User { UserName = "Anna", Selected = false } };
dataGridView1.DataSource = users;
}
//On delete
private void btnDelete_Click(object sender, EventArgs e)
{
//get data back from the source
var source = dataGridView1.DataSource as List<User>;
var selectedItems = source.Where(x => x.Selected).ToList();
foreach (var item in selectedItems)
{
//perform the delete
}
}

c# save data from datagridview to database

I would like to edit my database record from datagridview and save from there. What properties do i need to declare to enable me to edit the datagrid? And button2 is my save button, how do i update to the database? Someone please help me thanks!
{
//Get ID
string strTagIds = string.Empty;
//Connection to datebase
string c1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
OleDbConnection con = new OleDbConnection(c1);
}
private void button1_Click(object sender, EventArgs e)
{
//button1.Click += new EventHandler(dataGridView1_CellContentClick);
//Bind button
string txt = textBox1.Text;
string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
string strSqlStatement = string.Empty;
strSqlStatement = "SELECT * FROM jiahe WHERE [User] = '" + txt + "'";
OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSqlStatement, objConnection);
DataSet ds = new DataSet();
objAdapter.Fill(ds);
DataTable dt = ds.Tables[0];
dataGridView1.DataSource = dt.DefaultView;
try
{
if (dt.Rows.Count == 1)
{
string strLine = string.Empty;
string strUser = string.Empty;
foreach (DataRow dr in dt.Rows)
{
string strTags = dr["Tag ID"].ToString();
strUser = dr["User"].ToString();
string strAge = dr["Age"].ToString();
string strPhoneNumber = dr["Phone Number"].ToString();
// prepare command string
string selectString = #"SELECT Status FROM jiahe where [User] = '" + textBox1.Text + "'";
// 1. Instantiate a new command with command text only
OleDbCommand cmd = new OleDbCommand(selectString, objConnection);
// 2. Set the Connection property
cmd.Connection.Open();
// 3. Call ExecuteScalar to send command
string str = cmd.ExecuteScalar().ToString();
cmd.Connection.Close();
}
}
else
{
if (dt.Rows.Count == 0)
{
MessageBox.Show("Invalid input!");
}
}
}
catch (Exception)
{
MessageBox.Show("Error!");
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, EventArgs e)
{
//dataGridView1.BeginEdit(true);
//MessageBox.Show("Hello");
}
private void button2_Click(object sender, EventArgs e)
{
}
You need datagridview cell content value changed. You should make a string which will be updated each time you edit a row with the ID/index of the selected row. Then you can make an update to the database when the button2 is clicked.

Categories

Resources