C# SQL data to label control? - c#

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();
}
}

Related

c# display Access Database in DataGridView

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;

C# - Datagridview does not show data from MySQL

I have a datagridview which should contain all users in mysql database. For my problem, it adds rows based on the number of rows in the MySQL, but does not show any data on it. see image below (i have 2 rows in database):
screenshot
Here's my code that I've tried:
using MySql.Data.MySqlClient;
namespace SampleDatabaseQueries
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
MySqlConnection conn;
MySqlCommand cmd;
private void Main_Load(object sender, EventArgs e)
{
string connString = "server=localhost;user=root;password=;database=test_db";
conn = new MySqlConnection(connString);
showData();
}
public void showData()
{
string query = "SELECT * FROM test_db.users;";
cmd = new MySqlCommand(query, conn);
conn.Open();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable dTable = new DataTable();
adapter.Fill(dTable);
dgUsers.DataSource = dTable;
conn.Close();
}
}
}
EDIT: above code works, data was already loaded but it adds another column so I did not see at first (as you can see the long horizontal scroll on the above screenshot). To solve that, I removed the columns I manually added and changed my query to:
SELECT username AS Username, password AS Password FROM test_db.users;
Thank you!
Replace this:
MySqlDataAdapter adapter = new MySqlDataAdapter();
With:
using (MySqlDataAdapter reader = new MySqlDataAdapter(cmd))
{
adapter.Fill(dTable);
}
EDIT
For further improvement you could make a database connection class, i suppose you are using the MySql connector from oracle so you can check out their documentation on how to do this. Here is a link that can get you started on the most basic things like connecting and filling datatables: MySql connector documentation
EDIT 1
As you said my solution did not work, here is another one that I just tested and should work.
DataTable dTable = new DataTable();
conn.Open();
string query = "SELECT * FROM test_db.users;";
MysqlCommand cmd = new MySqlCommand(query, conn);
using (MySqlDataAdapter reader = new MySqlDataAdapter(cmd))
{
adapter.Fill(dTable);
}
dgUsers.DataSource = dTable;
conn.Close();
This should work. If the datatable is not showing any rows(Empty rows means it found something), then there is a different problem, maybe your database is empty.

Crystal Report in c# window application

Here is my code to set data on my crystal report but data is not comin in data set but with the same time dataset is fill for datagridview. please help me. thanks in advance
private void button1_Click(object sender, EventArgs e)
{
ReportDocument crystalrpt = new ReportDocument();
crystalrpt.Load(#"E:\c#\Date_day\Date_day\CR1.rpt");
Rst_PrntDataSet prnt = Getdata("select * from dbo.EMPL_TRN");
crystalrpt.SetDataSource(prnt);
CRV1.ReportSource = crystalrpt;
CRV1.Refresh();
}
private Rst_PrntDataSet Getdata(string qry)
{
string cs = ConfigurationManager.ConnectionStrings["Rst"].ConnectionString;
SqlCommand cmd = new SqlCommand(qry);
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
cmd.Connection = con;
da.SelectCommand = cmd;
using (Rst_PrntDataSet prnt = new Rst_PrntDataSet())
{
da.Fill(prnt, "tbl1");
return prnt;
}
}
}
}
Are you change any db object after creating this report i.e. your report is upto date with database.
If yes, then please check in result in design mode by passing value (just F5 to view result).
If no, then simple go to "Database" menu -> "update database" and follow the step as below link
http://www.softwareforces.com/Support/Learning-Center/Step-by-Step/rpt-Inspector/Changing-Data-source-and-Database-Crystal-Reports-Dev-to-QA-to-Production

C# mysql UPDATE and SELECT in one button

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) + "";
}
}
}

Loading combobox from database in C#

I am creating an application, where I can add a customer's first name, last name, email, the date, service type (pc repair), the technician PC brand, pc type, type of OS, and the problem with the computer. I am able to insert data into the MySQL database using phpMyAdmin.
However, I a stuck on this part. I am trying to view the service order that was just created. I would like to load the combobox by the last name of the customer, and once I click on the customer's name, it populates all the fields that were mentioned above and the service number that it was inserted into the database. I am having issues loading the combobox and texfields.
Any ideas are appreciated! If a combobox is a bad idea and there is a better way, please let me know! I tried this code, but SQLDataAdapter is not working for me. I somehow can't find an example that I can relate too.
private void cbViewServices_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbViewServices.SelectedIndex >- 1)
{
string lastName = cbViewServices.SelectedValue.ToString();
MySqlConnection conn = new MySqlConnection("server=localhost;uid=******;password=**********;database=dboserviceinfo;");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select distinct LastName from tserviceinfo where LastName='" + lastName + "'", conn);
DataSet ds = new DataSet();
da.Fill(ds); conn.Close();
}
}
I do not recommend using the 'Lastname' as a parameter to load your details since that field most likely isn't unique. Unless that is the case in your program.
This sample does the following:
Load customer ID (or lastname in your case) to a combobox.
Handle the combobox's change event and pass it as a parameter to a
method that will use that to load the details.
Load the customer details using the passed parameter.
A couple of guidelines:
Enclose disposable objects in a 'using' statement so it will be
disposed properly.
Do not use string concatenation to create your SQL statements. Use
SQL parameters instead, that way you'll avoid SQL injection and make
your code clearer.
Take a look at MySQL .NET connector provider documentation for best practices.
//Load customer ID to a combobox
private void LoadCustomersId()
{
var connectionString = "connection string goes here";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "SELECT Id FROM Customers";
using (var command = new MySqlCommand(query, connection))
{
using (var reader = command.ExecuteReader())
{
//Iterate through the rows and add it to the combobox's items
while (reader.Read())
{
CustomerIdComboBox.Items.Add(reader.GetString("Id"));
}
}
}
}
}
//Load customer details using the ID
private void LoadCustomerDetailsById(int id)
{
var connectionString = "connection string goes here";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "SELECT Id, Firstname, Lastname FROM Customer WHERE Id = #customerId";
using (var command = new MySqlCommand(query, connection))
{
//Always use SQL parameters to avoid SQL injection and it automatically escapes characters
command.Parameters.AddWithValue("#customerId", id);
using (var reader = command.ExecuteReader())
{
//No customer found by supplied ID
if (!reader.HasRows)
return;
CustomerIdTextBox.Text = reader.GetInt32("Id").ToString();
FirstnameTextBox.Text = reader.GetString("Firstname");
LastnameTextBox.Text = reader.GetString("Lastname");
}
}
}
}
//Pass the selected ID in the combobox to the customer details loader method
private void CustomerIdComboBox_SelectedIndexChanged(object s, EventArgs e)
{
var customerId = Convert.ToInt32(CustomerIdComboBox.Text);
LoadCustomerDetailsById(customerId);
}
I'm not entirely sure if this is what your looking for but most of the guidelines still applies.
Hope this helps!
Try something like this to bind data to the combo box:
public void ListCat()
{
DataTable linkcat = new DataTable("linkcat");
using (SqlConnection sqlConn = new SqlConnection(#"Connection stuff;"))
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT LastName FROM list WHERE LastName <> 'NULL'", sqlConn))
{
da.Fill(linkcat);
}
}
foreach (DataRow da in linkcat.Rows)
{
comboBox1.Items.Add(da[0].ToString());
}
}
Taken from my own question.
SqlDataAdapter is used to communicate with SQL Server rather than MySQL.
Try the following:
MySqlDataAdapter da = new MySqlDataAdapter("select distinct LastName from tserviceinfo where LastName='" + lastName + "'", conn);
We can also use while loop. When completing the database connection after the SQLDatareader we can use while loop.
"userRead " is SQLData reader
while (userRead.Read())
{
cboxReportNo.Items.Add(userRead[1].ToString());
}
bind your dataset in ComboBox DataSource
this.comboBox1.DataSource = ds;
this.comboBox1.DisplayMember = "LastName";
this.comboBox1.ValueMember = "Id";
this.comboBox1.SelectedIndex = -1;
this.comboBox1.AutoCompleteMode = AutoCompleteMode.Append;
this.comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
//USING
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace YourNamespace
{
//Initialization
string connetionString = null;
SqlConnection cnn;
SqlCommand cmdDataBase;
SqlDataReader reader;
DataTable dt;
public frmName()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
FillComboNameOfCombo();
}
void FillcmbNameOfCombo()
{
string sqlQuery = "SELECT * FROM DATABASENAME.[dbo].[TABLENAME];";
connetionString = "Data Source=YourPathToServer;Initial Catalog=DATABASE_NAME;User ID=id;Password=pass";
cnn = new SqlConnection(connetionString);
cmdDataBase = new SqlCommand(sqlQuery, cnn);
try {
cnn.Open();
reader = cmdDataBase.ExecuteReader();
dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("COLUMN_NAME", typeof(string));
dt.Load(reader);
cnn.Close();
cmbGender.DataSource = dt;
cmbGender.ValueMember = "ID";
cmbGender.DisplayMember = "COLUMN_NAME";
dt = null;
cnn = null;
cmdDataBase = null;
connetionString = null;
reader = null;
}
catch (Exception ex) {
MessageBox.Show("Can not open connection ! " + ex.ToString());
}
}
}

Categories

Resources