Im beginner in C#, but i have to make one software for friend. Its for generating numbers (they are in mysql). I have number in label and button. This button is for generate next number from MySQL (it SELECT number from database, which was not used).
My code:
private void button1_Click(object sender, EventArgs e)
{
string input = label1.Text.Trim();
string conn = "server=46.28.110.147;user=______;password=________;database=________;";
MySqlConnection myconn = new MySqlConnection(conn);
string sql = "SELECT numbers FROM domestic WHERE used=0 ORDER BY numbers LIMIT 1";
string sq2 = "UPDATE domestic SET used = 1 WHERE numbers = '" + label1.Text +"'";
MySqlDataAdapter da = new MySqlDataAdapter(sql, myconn);
MySqlCommand cmd = new MySqlCommand(sq2, myconn);
DataTable dt = new DataTable();
da.Fill(dt);
myconn.Open();
cmd.ExecuteNonQuery();
myconn.Close();
label1.Text = dt.Rows[0][0] + "";
}
Problem is when i click on button.
1) click on button - it make UPDATE (without SELECT) (it set used = 1 to number in database, which is in label)
2) click on button again - it make only SELECT (it takes next number from databse with used = 0)
3) click on button - it make only UPDATE (without SELECT)
4) clcik on button - AGAIN from step 2 to 3
Please, can you tell me, how can i do both operations (UPDATE and SELECT) in only one click?
Thanks and sorry for my bad english.
Your code looks like it currently behaves as follows:
Defines SELECT statement using a constant SQL query.
Defines UPDATE statement using the content of the label text (maybe empty?)
Fills a datatable with a MySqlDataAdapter. It must be recovering the first available number from your database.
Opens a connection and executes the update.
Recovers de first column of first datarow filled in point 3.
I think that the problem in this case is that you are mixing code to reach the solution. Try this:
Define SELECT statement using a constant SQL query.
Fill a datatable with a MySqlDataAdapter.
Recover the first column of first datarow filled in point 2 and populate value to the label text.
Define UPDATE statement using the content of the label text (this
time has the number recovered in the last step.
Open a connection and execute the update.
Something like...
private void button1_Click(object sender, EventArgs e)
{
string input = label1.Text.Trim();
string conn = "server=46.28.110.147;user=______;password=________;database=________;";
MySqlConnection myconn = new MySqlConnection(conn);
string sql = "SELECT numbers FROM domestic WHERE used=0 ORDER BY numbers LIMIT 1";
MySqlDataAdapter da = new MySqlDataAdapter(sql, myconn);
DataTable dt = new DataTable();
da.Fill(dt);
label1.Text = dt.Rows[0][0] + ""; // Recovers the value and puts into label.
MySqlCommand cmd = new MySqlCommand(sq2, myconn);
string sq2 = "UPDATE domestic SET used = 1 WHERE numbers = '" + label1.Text +"'";
myconn.Open();
cmd.ExecuteNonQuery(); // Updates database to set used = 1 for recovered number.
myconn.Close();
}
Try this:
private void button1_Click(object sender, EventArgs e)
{
string input = label1.Text.Trim();
string conn = "server=46.28.110.147;user=______;password=________;database=________;";
string sql = "SELECT numbers FROM domestic WHERE used=0 ORDER BY numbers LIMIT 1; UPDATE domestic SET used = 1 WHERE numbers = #numbers";
MySqlConnection myconn = new MySqlConnection(conn);
MySqlCommand cmd = new MySqlCommand(sql, myconn);
MySqlDataAdapter da = null;
DataSet ds = null;
DataTable dt = null;
cmd.Parameters.Add("numbers", SqlDbType.VarChar, 50).Value = input;
da = new MySqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count > 0) {
if (ds.Tables(0).Rows.Count > 0) {
dt = ds.Tables(0);
label1.Text = dt.Rows(0)(0) + "";
}
}
}
Related
First of all, here is my code:
private void Form5_Load(object sender, EventArgs e)
{
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\Users\name\Documents\myprogramms\example.accdb";
string strSql = "Select * from score";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
data_example.DataSource = scores;
}
My goal is to display the data out of a MS Access Database. My codes has no error messages, but everytime I try to open the Data Grid View its completely empty.
your code snippet looks good. I cannot see any obvious issue.
Try to put breakpoint at the end of your method and check if datatable contains rows and rows contains any values in ItemArray.
Make sure your data_example DataGridView control is set AutoGenerateColumns = true (default) and check you have no other data source defined for your data_example DataGridView control. This code works for me.
private void Form1_Load(object sender, EventArgs e)
{
data_example.AutoGenerateColumns = true;
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\aaa\CinemaBooking.accdb";
string strSql = "Select * from Booking";
using (OleDbConnection con = new OleDbConnection(strProvider))
{
using (OleDbCommand cmd = new OleDbCommand(strSql, con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
con.Open();
var scores = new DataTable();
da.Fill(scores);
data_example.DataSource = scores.DefaultView;
con.Close();
}
}
}
}
Maybe you can try to fill dataset with adapter and then use named table as datasource:
var dtSet = new DataSet();
da.Fill(dtSet, "Booking");
data_example.DataSource = dtSet.Tables["Booking"].DefaultView;
Can anyone tell me why this isn't working? I don't get an error in the code, but the information (month, day) doesn't show up in the labels. The connection is active, the data is there. It just will not display.
The listbox (listNames) is populated from the database, and that works fine. What I want is for the MONTH and DAY information from the selected record from listbox to display as labels.
Thanks for any help.
private void listNames_SelectedIndexChanged(object sender, EventArgs e)
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM members WHERE Name = " + listNames.SelectedItem.ToString(), connection))
{
DataTable showlistTable = new DataTable();
DataSet info = new DataSet();
adapter.Fill(showlistTable);
adapter.Fill(info);
labelDetailsMonth.Text = info.Tables[0].Rows[0]["Month"].ToString();
labelDetailsDay.Text = info.Tables[0].Rows[0]["Day"].ToString();
}
}
You need single quotes around string literals in SQL (your listNames.SelectedItem value). The best way to do this is by avoiding the string literal entirely and using a query parameter. This will also fix the gaping sql injection security hole:
private void listNames_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "SELECT * FROM members WHERE Name = #Name";
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(sql, connection))
{
//guessing at column type/length here
adapter.SelectCommand.Parameters.Add("#Name", SqlDbType.NVarChar, 20).Value = listNames.SelectedItem;
DataSet info = new DataSet();
adapter.Fill(info);
labelDetailsMonth.Text = info.Tables[0].Rows[0]["Month"].ToString();
labelDetailsDay.Text = info.Tables[0].Rows[0]["Day"].ToString();
}
}
I have stored some number data under column name Value in the tblV table of my database. I want to put the data from that column Value into textbox1.
But whenever I click the button it shows Column 'Value' does not belong to table error even though there is column Value in the table. What is causing this problem?
The first one is class and second one is the code on button click event.
public DataTable GetMaxno(decimal Licenseno)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;");
string sql = "select Max(Value) from tblv where Licenseno=#licenseno";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Licenseno",Licenseno );
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
da.Fill(DT);
return DT;
}
tryv tv = new tryv();
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = tv.GetMaxno(Convert.ToDecimal(textBox2.Text));
if (dt.Rows.Count > 0)
{
textBox1.Text= dt.Rows[0]["Value"].ToString();
}
}
Reason might be that your query does not return any aliases as Value. You can solve this with select Max(Value) as Value but instead of that, use ExecuteScalar instead which is exactly what you want. It returns first column of the first row.
A few things more;
Use using statement to dispose your connection and command.
Do not use AddWithValue. It may generate unexpected and surprising result sometimes. Use Add method overloads to specify your parameter type and it's size.
public int GetMaxno(decimal Licenseno)
{
using(var con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;")
using(var cmd = con.CreateCommand())
{
cmd.CommandText = "select Max(Value) from tblv where Licenseno = #licenseno";
cmd.Parameters.Add("#licenseno", SqlDbType.Decimal).Value = Licenseno;
con.Open();
return (int)cmd.ExecuteScalar();
}
}
Then you can do;
textBox1.Text = tv.GetMaxno(Convert.ToDecimal(textBox2.Text)).ToString();
try
string sql = "select Max(Value) as Value from tblv where Licenseno=#licenseno";
I’ve two comboboxes which should contain two different informations.
1.cb1: select table_name from information_schema.tables (this display multiple tables)
2.cb2: should populate it with a column name.
Example: I've three tables in cb1 with the same attributes but have different values at the column EmpName (tblLondon,tblBerlin,tblRom,...)
Now I wanna display in second comboboxe the column EmpName dynamically whenever I choose a table in first combobox.
cb1[tblLondon] cb2[John,Mavis,Chris,Mike..]
OR
cb1[tblBerlin] cb2[Günther,Peter, Sophie,Sunny, ..]
Can u plz help me out
string C = ConfigurationManager.ConnectionStrings[""].ConnectionString;
SqlConnection con = new SqlConnection(C);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_NAME ASC");
try
{
// Open connection, Save the results in the DT and execute the spProc & fill it in the DT
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
cbTbl.DisplayMember = "TABLE_NAME";
cbTbl.ValueMember = "TABLE_NAME";
//Fill combobox with data in DT
cbTbl.DataSource = dt;
// Empty bzw. clear the combobox
cbTbl.SelectedIndex = -1;
This code is working and populating my cb1 (combobox)
And now i don't really know how to go about with cb2
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
if I understand you correctly, and if you have this data in SQL server or other database you should use SelectedIndexChange event and load item for that Id (use Display Member and Value Member for match Id).
take a look at this.it might help you
Edit :
you can do this with below code : (if you don't use database)
you should use this code in cb1.SelectedIndexChange (or value)
var cb2items = new Dictionary<int, string> {{1, "Name"}, {1, "anotherName"},{2,"Name"},{2, "anotherName"}}; // use the number for parent Id in cb1
foreach (var item in cb2items)
{
if (item.Key == int.Parse(comboBox1.SelectedValue.ToString()))
{
comboBox2.Items.Add(item);
}
}
Edit 2 :
use this code in cb1.SelectedValueChange:
string C = ConfigurationManager.ConnectionStrings[""].ConnectionString;
SqlConnection con = new SqlConnection(C);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("SELECT ... WHERE TableName = cb1.SelectedValue");
spProc & fill it in the DT
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
cbTbl.DisplayMember = "TABLE_NAME";
cbTbl.ValueMember = "TABLE_NAME";
cbTb2.DataSource = dt;
and you also can create a procedure that send back the items from table name as input. if you use procedure, your code perform better.
Edit 3 :
put this code in cbTb2.SelectedValueChange event :
try
{
int a = int.Parse(cbTB2.SelectedValue.ToString());
}
catch { }
You might want to see combobox's events, "SelectedIndexChanged" or "SelectedValueChanged" should do it
I am trying to delete selected data from datagrid and database at the same time when user clicks on "Delete". It is not working and error message shows that "Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index"
Can anyone help me out this coding.
private void btnDeleteCustomer_Click(object sender, EventArgs e)
{
string strSqlConnection = #"Data Source = KK\SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = JeanDB";
if ((dgvCustomerView.Rows.Count>0) && (dgvCustomerView.SelectedRows[1].Index != dgvCustomerView.Rows.Count))
{
SqlConnection sqlconn = new SqlConnection(strSqlConnection);
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = #iCustomerID";
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);
sqlconn.Open();
DataTable dtEmployee = new DataTable("Customers");
sdaCustomer.Fill(dsCustomers, "Customers");
sqlconn.Close();
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
MessageBox.Show("Deleted Successfully");
}
}
Instead of Remove you can rebind grid:
dgvEmpView.DataSource = dsCustomers;
dgvEmpView.DataBind();
MessageBox.Show("Deleted Successfully");
and for deletion ExecuteNonQuery is used:
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
sqlconn.Open();
cmd.ExecuteNonQuery();
Unless you have two rows selected referencing the SelectedRows[1] is wrong. The array indexes start always with zero. (Probably it is just a type because the other lines references correctly the row to be deleted)
if ((dgvCustomerView.Rows.Count>0) &&
(dgvCustomerView.SelectedRows[0].Index != dgvCustomerView.Rows.Count))
{
....
but then, to delete the row in the database, you don't need to use an SqlDataAdapter.
You could work directly with a SqlCommand
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = #iCustomerID";
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
cmd.Parameters.AddWithValue("#iCustomerID", iCustomerID);
sqlconn.Open();
cmd.ExecuteNonQuery();
finally you could simply remove the selected row from the grid without further query
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
If do not use sql parameters then use plain sql query.
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = "+ iCustomerID.ToString();
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);