I have two combobox in my form, using a mysql connection to a remote server. The first combobox populated nicely. However, I need the indexid since that is a foreign key to populate a second combobox. Based on the selection, it will change the data in the second combo (for the xample, i the first combo is for car makes, then the models of each make gets filled, so if I choose Nissan, the models will then have Altima, Maxima, Sentra, ... but if I chose Toyota, the combo will then show Corolla, Camry, Prius, ...)
My foreign key is always -1 for some reason. I am using the selectindex change method, but it keeps crashing/ bc the value is always -1.
I am very new to MySQL in C# and eager to learn. Any help is appreciated. The code is below.
private void cboMake_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboMake.SelectedIndex >= 0)
cboModel.Enabled = true;
else
cboModel.Enabled = false;
// get the foreign key value of the model id to get the make for each brand to populate here
// MessageBox.Show(cboModel.ValueMember);
// right now selectindex always shows -1. why?
// if it changes, you need to then enable the right cbo, else, disable.
// but also, you need the mid, fk, so you can then do a new sql statement with the where clause to populate it.
int fk = cboModel.SelectedIndex;
string connStr = "server=123.456.7.8;user=root;database=car;port=3306; password=nowayjose";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "SELECT * FROM cs_model WHERE mid='fk'";
MySqlCommand cmd = new MySqlCommand(sql, conn);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
cboMake.DataSource = dt;
cboMake.DisplayMember = "model";
cboMake.ValueMember = "mmid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MySQL Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
}
private void frmMain_Load(object sender, EventArgs e)
{
string connStr = "server=123.456.7.8;user=root;database=car;port=3306; password=nowayjose";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "SELECT * FROM cs_make";
MySqlCommand cmd = new MySqlCommand(sql, conn);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
cboMake.DataSource = dt;
cboMake.DisplayMember = "make";
cboMake.ValueMember = "mid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MySQL Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
}
Correct me if I'm wrong, but considering code provided, just a guess :
private void cboMake_SelectedIndexChanged(object sender, EventArgs e)
{
int fk = cboModel.SelectedIndex; // ?????
.....
}
You access here cboModel, which is not that one whom item was actually selected. At least lookin on event name cboMake_SelectedIndexChanged, seems to me that you should look on cboMake selected index.
Hope this helps.
private void cboMake_SelectedIndexChanged(object sender, EventArgs e)
{
int foreignKey = (int)cboMake.SelectedIndex +1; // i forgot to cast the int from string since the database was tinyint, it still returns string in c#
string fk = foreignKey.ToString(); // since i need the string for the query, back it goes, but i needed to do arithmetic
string connStr = "server=10.18.30.1;user=notroot;database=car;port=3306;password=password";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "SELECT * FROM cs_model WHERE mid=" + fk; // forgot to escape out of the string (used to php $var style within double quotes)
MySqlCommand cmd = new MySqlCommand(sql, conn);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
cboModel.DataSource = dt; // i had cboModel by a silly mistake
cboModel.DisplayMember = "model";
cboModel.ValueMember = "mmid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MySQL Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
}
Related
I made a simple application that displays data from a database in a DataGridView, users can add rows, delete rows, update values and save the changes.
Now, let's say User A modifies a value in row 8 and saves. User B adds 50 rows and wants to modify a cell in row 8 also. When user B saves, DBConcurrencyException occurs and all his work is lost.
Considering the way people will use this app, this scenario should not happen but there is still a small chance.
Is it possible to keep the added rows when the DBConcurrencyException is raised ? Or should I just tell the users to save as often as possible ?
Here is the relevant code :
private BindingSource bindingSource = null;
private SqlCommandBuilder commandBuilder = null;
string conStringLocal = "xxxxxxxxxxx";
SqlCommand command;
SqlDataAdapter dataAdapter;
DataTable dataTable = new DataTable();
public Form1()
{
InitializeComponent();
DataBind();
}
private void DataBind()
{
dataGridViewCND.DataSource = null;
dataTable.Clear();
string query = "SELECT * FROM myTable";
SqlConnection con = new SqlConnection(conStringLocal);
try
{
con.Open();
command = con.CreateCommand();
command.CommandText = query;
dataAdapter = new SqlDataAdapter(query, con);
commandBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(dataTable);
bindingSource = new BindingSource { DataSource = dataTable };
dataGridViewCND.DataSource = bindingSource;
this.dataGridViewCND.Columns["id"].Visible = false;
this.dataGridViewCND.Sort(this.dataGridViewCND.Columns["Date"], ListSortDirection.Ascending);
}
catch (Exception ex)
{
// GENERIC ERROR MESSAGE
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
dataGridViewCND.EndEdit();
dataAdapter.Update(dataTable);
DataBind();
// UPDATE SUCCESS MESSAGE
}
catch(DBConcurrencyException ex)
{
// CONCURRENCY ERROR MESSAGE
DataBind();
}
catch (Exception ex)
{
// GENERIC ERROR MESSAGE
DataBind();
}
}
I am working on a visual web part that does simple CRUD operations and I have this strange behavior in Page_load().
I grab first record from query and assign some text fields when page is loaded. When I clear the form and update the form with new different inputs, those text fields remember the first values and ignores newly entered data.
Am I missing anything in Page_load() when I display data when the page is loaded?
public partial class VisualWebPart1UserControl : UserControl
{
string connstr = AdminDashBoard.Utility.GetConnectionString();
private DataSet sqlDst = new DataSet();
private static int RowNo = 0;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(connstr);
string strQuery = "xxxxxxxxxxxxxxxxxxxxxx";
try
{
conn.Open();
SqlCommand sqlCmd = new SqlCommand(strQuery, conn);
sqlCmd.CommandType = CommandType.Text;
SqlDataAdapter sqlAdap = new SqlDataAdapter(sqlCmd);
sqlAdap.Fill(sqlDst);
//these fields remember first assigned data!!!
this.TextBox1.Text = sqlDst.Tables[0].Rows[RowNo][0].ToString();
this.TextBox2.Text = sqlDst.Tables[0].Rows[RowNo][1].ToString();
this.TextBox3.Text = sqlDst.Tables[0].Rows[RowNo][2].ToString();
this.DateTimeControl1.SelectedDate = Convert.ToDateTime(sqlDst.Tables[0].Rows[RowNo][3].ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
conn.Close();
conn.Dispose();
}
}
thanks in advance
I have fetched the data from SQL server to datagridview but I don't know how to change the cell value. I have to change the fetched value 1 and 0 to available and unavailable. here is my code for fetching data ... please help.
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
SqlCommand cmd = new SqlCommand("Select id as 'Book ID',name as 'Name' , status as 'Status' from book where Name = #name", con);
cmd.Parameters.AddWithValue("#name", txtFirstName.Text);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
dataGridView1.DataSource = bsource;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
Please find below answer
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
string sSql=#"Select id as 'Book ID',name as 'Name' ,
Case when status=0 then 'unavailable' else 'available '
End as 'Status' from
book where Name ='"+txtFirstName.Text +"'"
SqlCommand cmd = new SqlCommand(sSql, con);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
First of all, try to store your queries in variables. This will help you in the long run. Also, it is good practise to check whether you are connected or not before trying to send a query away to the server. It is important to remeber that when you fetch data from your server, it will most likely be seen as a string, so if you want to compare it as a number, you need to convert it first.
What you could do is something similar to what i've written below. You count the amount of answers your query returns, then loop through them and check whether they are 0 or 1. Then just replace the value with Avaliable or Unavaliable.
if (dbCon.IsConnect()){
MySqlCommand idCmd = new MySqlCommand("Select * from " + da.DataGridView1.Text, dbCon.Connection);
using (MySqlDataReader reader = idCmd.ExecuteReader()){
// List<string> stringArray = new List<string>(); // you could use this string array to compare them, if you like this approach more.
while (reader.Read()){
var checkStatus= reader["Status"].ToString();
Console.WriteLine("Status: " + checkStatus.Split(' ').Count()); //checks how many items you've got.
foreach (var item in checkStatus.Split(' ').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray()){
var item2 = 0.0; // your 0 or 1 for avaliable or unavaliable..
try{
item2 = double.Parse(item.ToString());
if(strcmp(item2,'0') == 1){ //assuming you only have 0's and 1's.
item2 = "unavaliable";
}else{
item2 = "avaliable";
}
}
catch (Exception){
//do what you want
}
Console.WriteLine("item: " + item2);
}
}
dbCon.Close();
}
}
return //what you want;
}
I have this datadridview that display data in a SQL database table. In here I have used a SQLDataAdapter and a DataTable(). Please refer the below code snippet.
private void btnSrcDataID_Click(object sender, EventArgs e)
{
try
{
dgvInsertInfo.Refresh();
SqlComm = new SqlCommand();
SqlComm.Connection = SqlConn;
SqlComm.CommandText = ("SELECT * FROM MyDataTable WHERE DataID = #SDataID");
SqlComm.Parameters.AddWithValue("#SDataID", txtDataID.Text);
SqlDataTable = new DataTable();
SqlAdapt = new SqlDataAdapter(SqlComm);
//DataSet dsQryDataId = new DataSet();
SqlAdapt.Fill(SqlDataTable);
//Passing data to DatagridView
dgvInsertInfo.DataSource = SqlDataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I think the issue is with either the SQL QueryString or SqlAdapt.Fill(), but I cannot understand the issue. Could you please someone help me on this.
Thanks,
Chiranthaka
Actually in my case the error occurred due to a typo error when passing the value to the Scalar variable #SDataID. So that the SQL statement's syntax is correct. Please refer the correct SQL statement below.
private void btnSrcDataID_Click(object sender, EventArgs e)
{
try
{
dgvInsertInfo.Refresh();
SqlComm = new SqlCommand();
SqlComm.Connection = SqlConn;
SqlComm.CommandText = "SELECT * FROM MyDataTable WHERE (DataID LIKE #SDataID)";
SqlComm.Parameters.AddWithValue("#SDataID", txtSrcDataID.Text);
SqlDataTable = new DataTable();
SqlAdapt = new SqlDataAdapter(SqlComm);
SqlAdapt.Fill(SqlDataTable);
dgvInsertInfo.DataSource = SqlDataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Now the data is populating correctly in the DataGridView.
Thanks.
m developing application for my office and in my application there is a datagrid view that linked to a mysql database. local users can update the database using datagridview but they cant delete any recodes. i want to implement a method that user's are select exact raw in the datagridview and delete it as well as delete the database record soon. i managed to make select and delete datagridview row using below code but it not update the database
private void button60_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
}
}
and this is my connection string that i normally use to view the database data in datagrid view. i don't have good knowledge to combined these two.can someone please show me how to do that
my connection string
private void showdatagrid()
{
string constring = string.Format("datasource='{0}';username=******;port=3306;password=***********;Connect Timeout=20000;Command Timeout=28800", dbserverip.Text);
MySqlConnection conwaqDatabase = new MySqlConnection(constring);
MySqlCommand cmdwaqDatabase = new MySqlCommand(" select * from warit.loans ; ", conwaqDatabase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdwaqDatabase;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try this code
private void button60_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
{
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
int loannumber = dataGridView1.Rows[oneCell.RowIndex].Cells['index of loannumber column in datagridview'].Value; // assuming loannmber is integer
string username = dataGridView1.Rows[oneCell.RowIndex].Cells['index of username column in datagridview'].Value; // assuming username is string
/* Now create an object of MySqlConnection and MySqlCommand
* and the execute following query
*/
string query = string.Format("DELETE FROM table_name WHERE loannumber = {0} AND username = '{1}'", loannumber, username);
}
}
}
string connection = "server = URL; uid = user; pwd = password; database = database;";
using (MySqlConnection conn = new MySqlConnection(connection)) {
conn.Open();
string idLocRemv = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string removeVolCred = "DELETE FROM TableName WHERE ID = " + idLocRemv;
using (MySqlCommand command = new MySqlCommand(removeVolCred, fbcConn)) {
command.ExecuteNonQuery();
}
conn.Close();
}
Apply necessary exception handlers. (try catch finally)
Additionally, you will need to re-load DataGridView afterwards.