I need a help.
I searched and I tried a lot but I am too bad to make it work on my project by myself.
This is code for button-Seek. I want to make Seek-button to fill textbox by respective data.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
var Conn = new SqlConnection();
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
var Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = " + Number;
var DataAdapter = new SqlDataAdapter(Cmd);
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
}
}
And This is the data table.
This is what happens when I put 3 in the text box and press Seek-button.
So here, I want all text boxes to be filled by the data which I searched.
You will get only one row for the query right?
So give like that,
txtFirstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
txtLasttName.Text = DataSet.Tables[0].Rows[0]["LastName"].ToString();
Like this you need to assign the values to the respective text boxes.
There are three problem need to fix.
You forget to open the connection with DB,add Conn.Open(); before you excute sql command.
You need to add parameter to prevention SQL Injection
Please use using it will help you to use external resources to return the memory.
when the DataSet be filled you can get the data then fill in textbox
You can follow like this.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
using (var Conn = new SqlConnection())
{
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
using (var Cmd = new SqlCommand())
{
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = #Number";
Cmd.Parameters.AddWithValue("#Number", Number);
//You miss to add Conn.Open()
Conn.Open();
using (var DataAdapter = new SqlDataAdapter(Cmd))
{
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
//when the DataSet be filled you can get the data then fill in textbox
txt_firstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
}
}
}
}
}
Related
So I'm trying to create sort of an overview utility of sites, with different infos on each site.
I'd like to have a dropdown list / combobox, reading a sqldb and create items according to the db. Then I would like different textboxes to get populated with a value from a column.
Say my db table is called "AvSites" so far (just for the sake of it) i have "projectNr", "siteName", "siteClients" and "siteLicenses" columns I'd like each of these to populate some textbox / label somewhere.
I've tried the following, which kinda works, Ive had the code working most of the time, but the thing that defeats me is having the data change with the combobox item selected.
I hope you can help, and so here is my code so far (I have a login window, before this "main" program starts, just so you're not wondering)
And I'm quite new to C# so if there's something thats done inefficient thats the reason :) Im still learning.
namespace AvOverview{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
//btn_LogOut Click Event
this.Hide();
Form1 fl = new Form1();
fl.Show();
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void FrmMain_Load(object sender, EventArgs e)
{
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf";
SqlConnection con = new SqlConnection(cs);
con.Open();
string strCmd = "select * from AvSites";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
combo1.ValueMember = "id";
combo1.DisplayMember = "siteName";
combo1.DataSource = ds.Tables[0];
combo1.Enabled = true;
this.combo1.SelectedIndex = -1;
cmd.ExecuteNonQuery();
con.Close();
}
private void Combo1_SelectedIndexChanged(object sender, EventArgs e)
{
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf";
string strCmd = "select id from AvSites";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(strCmd, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{//this last part is solely for testing if the text changed the way I wanted.
label1.Text = dr.GetValue(1).ToString();
label2.Text = dr.GetValue(2).ToString();
label3.Text = dr.GetValue(0).ToString();
label4.Text = dr.GetValue(3).ToString();
You don't need to call the database again. All the info are in the current selected item.
When you set the DataSource of your combo to a datatable like you do in the click event each element of the combo is a DataRowView and from this element you can get all the info extracted from the database from your initial query
private void Combo1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView rv = Combo1.SelectedItem as DataRowView;
if(rv != null)
{
label1.Text = rv[1].ToString();
label2.Text = rv[2].ToString();
label3.Text = rv[0].ToString();
label4.Text = rv[3].ToString();
}
}
Side note: There are some improvements needed in your code.
First you should store the connection string in the config file and read it back with the ConfigurationManager class. Read about Configuration in NET
Second you shouldn't work with disposable objects like you do now. A disposable object should be disposed as soon as you have finished to use it. In particular the SqlConnection keeps valuable system resources both on your machine and on the server. You should start to use the using statement
string strCmd = "select * from AvSites";
using(SqlConnection con = new SqlConnection(.......))
using(SqlCommand cmd = new SqlCommand(strCmd, con)))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
combo1.ValueMember = "id";
combo1.DisplayMember = "siteName";
combo1.DataSource = ds.Tables[0];
combo1.Enabled = true;
this.combo1.SelectedIndex = -1;
// ??? not needed ==> cmd.ExecuteNonQuery();
// not needed with using ==> con.Close();
}
// Here the connection is closed and disposed and resources are released
I have set up a listbox called lboxsupplier, i have also created a data adapter which i then used to populate the supplier listbox. When i run the form the listbox is empty. I want the listbox to populate with supplier ID and company which i will then click on to populate another listbox with products.
Namespace Pennyburn_Greg
{
public partial class FormProcess : Form
{
SqlDataAdapter daSupplier;
DataSet dsPennyburnGreg = new DataSet();
SqlConnection conn;
SqlCommand cmdSupplierDetails;
SqlCommandBuilder cmdBSupplier;
DataRow drSupplier;
String connstr, sqlSupplier;
public FormProcess()
{
InitializeComponent();
}
private void FormProcess_Load(object sender, EventArgs e)
{
connstr = #"Data Source= arlene-pc; Initial Catalog= PennyburnGreg; Integrated Security=True";
//dataAdapter for supplier listbox
sqlSupplier = #"Select* from Supplier";
conn = new SqlConnection(connstr);
cmdSupplierDetails = new SqlCommand(sqlSupplier, conn);
daSupplier = new SqlDataAdapter(cmdSupplierDetails);
daSupplier.FillSchema(dsPennyburnGreg, SchemaType.Source, "Supplier");
}
private void filllboxsupplier(string str)
{
daSupplier.Fill(dsPennyburnGreg, "Supplier");
lboxsupplier.DataSource = dsPennyburnGreg.Tables["Supplier"];
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
}
}
}
First of all, why are you calling FillSchema, rather should be calling Fill method to get the data, like
daSupplier.Fill(dsPennyburnGreg, "Supplier");
Once you have the dataset filled, then in your FormProcess_Load() you can add the dataset as datasource to the listbox like
lboxsupplier.DataSource = dsPennyburnGreg.Tables["Supplier"]
First thing you need to do is loosely couple your UI and data a little bit. Try this code:
// Returns a DataTable of ALL suppliers
private DataTable GetSuppliers()
{
return GetSuppliers(0);
}
// Returns a DataTable of the given supplier
private DataTable GetSuppliers(int supplierId)
{
using (var connection = new SqlCommand())
{
connection.ConnectionString = #"Data Source= arlene-pc; Initial Catalog= PennyburnGreg; Integrated Security=True";
using (var command = new SqlCommand())
{
connection.Open();
command.CommandType = CommandType.Text;
command.Connection = connection;
if (supplierId == 0)
{
command.commandText = "SELECT * FROM Supplier";
}
else
{
command.commandText = "SELECT * FROM Supplier WHERE SupplierId=#id";
command.Parameters.AddWithValue("#id", supplierId);
}
using (var adapter = new SqlDataAdapter())
{
using (var ds = new DataSet())
{
adapter.SelectCommand = command;
adapter.Fill(ds);
if (ds.Tables.Count > 0)
return ds.Tables[0];
}
}
}
}
return null;
}
And now you can just do this:
lboxsupplier.DataSource = GetSuppliers(int.Parse(lboxsupplier.SelectedValue));
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
Or if you need all Suppliers, just do this:
lboxsupplier.DataSource = GetSuppliers();
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
This code will provide some separation. This is still not ideal, but beats what you had.
You're not doing anything with the listbox control in FormProcess_Load, so it will be empty when it first loads. I'm assuming you have lboxsupplier_Click bound to the Click event of lboxsupplier? If so, then you'll need to click on that listbox before it will populate the Dataset (which is a very odd user experience, but if that's truly what you need...). If lboxsupplier_Click isn't an event handler, then you're going to have to manually call it.
If it still isn't populating, then try running your query against the database directly, and make sure that it returns data and has columns named "Company" and "SupplierID"
i have a datagridview which loads mysql database table t_pi_clients on form load event,and i have another tab which contains textboxes of the respective columns of t_pi_client, which am able to get data from fullrowselect mode into those textboxes. now i want to update the database upon changes in the those textbox values. so far i've tried some process and gets my "entry saved" messageBox.show but nothing happens to database, so am hoping someone could help me out maybe am missing something thanks
public partial class frmMain : Form
{
MySqlConnection connection;
MySqlDataAdapter mySqlDataAdapter;
DataSet dt = new DataSet();
DataSet DS = new DataSet();
DataSet dg = new DataSet();
public frmMain()
{
InitializeComponent();
}
#region Main load
private void frmMain_Load(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Pigen"].ConnectionString;
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_Clients", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
kryptonDataGridView1.DataSource = DS.Tables[0];
kryptonDataGridView1.Columns[0].Visible = false;
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_msg_charge_Rate", connection);
DataSet dt = new DataSet();
mySqlDataAdapter.Fill(dt);
kryptonDataGridView2.DataSource = dt.Tables[0];
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_client_deposits", connection);
DataSet dg = new DataSet();
mySqlDataAdapter.Fill(dg);
kryptonDataGridView3.DataSource = dg.Tables[0];
}
}
//loads selected row data into textboxes
private void kryptonDataGridView1_DoubleClick(object sender, EventArgs e)
{
textboxClientCode.Text = kryptonDataGridView1.SelectedRows[0].Cells["ClientCode"].Value.ToString();
txtboxClientName.Text = kryptonDataGridView1.SelectedRows[0].Cells["ClientName"].Value.ToString();
txtboxPostalAddress.Text = kryptonDataGridView1.SelectedRows[0].Cells["PostalAdd"].Value.ToString();
txtboxTelephone.Text = kryptonDataGridView1.SelectedRows[0].Cells["Telephone"].Value.ToString();
txtboxFax.Text = kryptonDataGridView1.SelectedRows[0].Cells["Fax"].Value.ToString();
txtboxEmailAddress1.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd1"].Value.ToString();
txtboxEmailAddress2.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd2"].Value.ToString();
txtboxEmailAddress3.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd3"].Value.ToString();
txtboxWebsite.Text = kryptonDataGridView1.SelectedRows[0].Cells["Website"].Value.ToString();
txtboxChargeRate.Text = kryptonDataGridView1.SelectedRows[0].Cells["ChargeRate"].Value.ToString();
txtboxTotalDepo.Text = kryptonDataGridView1.SelectedRows[0].Cells["TotalDeposit"].Value.ToString();
txtboxAccountBal.Text = kryptonDataGridView1.SelectedRows[0].Cells["AccountBal"].Value.ToString();
txtboxEntrydate.Text = kryptonDataGridView1.SelectedRows[0].Cells["EntryDate"].Value.ToString();
}
now i tried this method to update but doesn't update database
private void kryptonbtnUpdate_Click(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Pigen"].ConnectionString;
using (MySqlConnection Conn = new MySqlConnection(connectionString))
if (Conn.State.ToString() != "Open")
{
}
else
{
connection.Open();
}
try
{
DataTable changes = ((DataTable)kryptonDataGridView1.DataSource).GetChanges();
if (changes != null)
{
MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
mySqlDataAdapter.Update(changes);
((DataTable)kryptonDataGridView1.DataSource).AcceptChanges();
mySqlDataAdapter.Update(DS);
}
// adapter.Update(rowsToUpdate);
// mySqlDataAdapter.Update(DS);
MessageBox.Show("Entry Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is just a pseudocode of what you need to do
string cmdText = #"UPDATE t_pi_Clients
SET ClientName = #ClientName,
PostalAdd = #PostalAdd,
Telephone = #Telephone,
Fax = #Fax,
.... etc ....
WHERE ClientCode = #ClientCode";
using(MySqlConnection cn = new MySqlConnection(.....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("#ClientName", txtboxClientName.Text);
cmd.Parameters.AddWithValue("#PostalAdd", txtboxPostalAddress.Text);
....etc etc...
cmd.Parameters.AddWithValue("#ClientCode", textboxClientCode.Text);
int rowsUpdated = cmd.ExecuteNonQuery();
if(rowsUpdated > 0)
{
// extract the code that loads DataGridView1 from the Form_Load
// and create a reusable method that you could call from here
}
}
First you build an sql command text with the UPDATE clause. I assume that your primary key (the field that uniquely identifies your records) is the ClientCode field.
Then create the connection and the command. Fill the command parameters collection with the parameters required by your text taking the values from the TextBoxes.
Call the ExecuteNonQuery to store the values.
If you succeed then you need to update or reload your datagridview. The best approach would be setting one by one the gridview cells of the current row with the new values from the textboxes, or you could simply extract the code used in form_load to fill the grid and make a new method that you could call from the button click event. (But this could be slower if you have many records)
I have 2 datagridview controls in a Windows Forms application.
I would like to get the info of a person when I select first datagridview cell or row to next datagridview:
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
adap3 = new SqlDataAdapter(#"SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id='"+DailyGV.CurrentRow+"'", con);
ds3 = new DataSet();
adap3.Fill(ds3, "dailyattendance");
dataGridView1.DataSource = ds3.Tables[0];
}
Im trying the above code. But it's not working.
I'm not too sure what DailyGV.CurrentRow is but basically you can use the RowHeaderMouseClick...see MSDN documentation. To use it, hook an event handler to it when initializing the form components (you can use VS designer as well...
dataGridView1.RowHeaderMouseClick += dataGridView1_RowHeaderMouseClick;
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
}
this event handler will get fired everytime you select a row header in the DataGridView control which will pass information about the event through an instance of the DataGridViewCellMouseEventArgs class (see MSDN documentation). This argument has a RowIndex property that provides the index of the row clicked which you can use to retrieve the values of the cells in that row...including the person id (if provided)...for example...
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
string personId = dataGridView1.Rows[e.RowIndex].Cells["PersonId"].Value;
//TODO: implement your own query to retrieve data for that person id
}
notice that you need to provide a proper column name when access the cells collection indexer...Cells["columnName"]
I will not give any description about the solution because Leo and Arsalan Bhatti has already suggested the solution. I am just telling you how your code should looks like and how it should be written.
string connectionString = consettings.ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
string empID = DailyGV.CurrentRow.Cells["employee_id"].Value.ToString();
SqlCommand Cmd = con.CreateCommand();
Cmd.CommandText = "SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id=#employee_id";
Cmd.Parameters.Add("#employee_id", SqlDbType.Int).Value = Int32.Parse(empID);
adap3 = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
adap3.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
catch
{}
}
try
{
cn.Open();
string query = "select employee_id,Employee_Name,Image_of_Employee from Employee_Details where employee_id='" + dataGridView1.SelectedCells[0].Value.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader sdr;
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
string aa = (string)sdr["employee_id"];
string bb = (string)sdr["employee_name"];
txtEmployeeID.Text = aa.ToString();
txtnameofemployee.Text = bb.ToString();
byte[] img=(byte[])sdr["Image_of_employee"];
MemoryStream ms=new MemoryStream(img);
ms.Seek(0,SeekOrigin.Begin);
pictureBox1.Image=Image.FromStream(ms); cn.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
You are passing the current row's index as employee id in SELECT query. Pass employee id for the selected record. Then it will work fine.
I'm using Visual Studio 2010 and C# to create a windows form with a combobox that should contain employees initials. I have spent the last few days searching through every solution I can find and I still can not get my combobox to populate.
This is what I've got as of now:
public static void FillComboBox(string Query, System.Windows.Forms.ComboBox LoggedByBox)
{
using (var CONN = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Documents\\Service Request Application\\bin\\Debug\\servicereq1.mdb"))
{
CONN.Open();
DataTable dt = new DataTable();
try
{
OleDbCommand cmd = new OleDbCommand(Query, CONN);
OleDbDataReader myReader = cmd.ExecuteReader();
dt.Load(myReader);
}
catch (OleDbException e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
LoggedByBox.DataSource = dt;
LoggedByBox.ValueMember = "ID";
LoggedByBox.DisplayMember = "Initials";
}
}
Then I call it when the form loads
private void Form1_Load(object sender, EventArgs e)
{
FillComboBox("select ID, Initials from [Fixers and Testers]", LoggedByBox);
}
When I run the program, the combobox is still blank. I'm positive that my column names and table names are correct. Any suggestions?
I finally got my ComboBox filled and I wanted to share what I changed for anyone else who stumbles across this question in their searches. After spending a bit more time searching through other questions and MSDN, I was able to come up with this.
private void LoadComboLogged()
{
AppDomain.CurrentDomain.SetData("DataDirectory",#"\\prod\ServiceRequests");
string strCon = #"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|\servicereq1.mdb";
try
{
using (OleDbConnection conn = new OleDbConnection(strCon))
{
conn.Open();
string strSql = "SELECT Initials FROM [Fixers and Testers] WHERE [Status] ='C'";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
DataSet ds = new DataSet();
adapter.Fill(ds);
loggedByComboBox.DataSource = ds.Tables[0];
loggedByComboBox.DisplayMember = "Initials";
loggedByComboBox.ValueMember = "Initials";
}
}
catch (Exception ex)
{
}
}
I also found that I needed to call
LoadComboLogged();
when I initialized my form. Without that line, the ComboBox would only show a blank dropdown list. Hope this helps someone else who runs into this problem.
Passing control to static method causing this issue. Instead of passing control to the method make that method returns the table and within the load method load the control.
SqlConnection con = new SqlConnection("Data Source=RUSH-PC\\RUSH;Initial Catalog=Att;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select name from userinfo", con);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr;
dr = dt.NewRow();
dt.Rows.InsertAt(dr, 1);
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "name";
comboBox1.DataSource = dt;
con.Close();
This may help you...
Good luck...:-)
Another possible solution would be to query and return a list of strings. Perhaps it may be less efficient, but it's what I used in a recent project of mine. Here's an example that would reside in a method, possibly called GetInitialsFromDatabase():
using(var conn = new MySqlConnection(connectionString)
{
conn.Open();
using(MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT Initials FROM [Fixers and Testers] WHERE [Status] ='C'";
MySqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
// initials is a List<String> previously defined (Assuming strings)
initials.Add(String.Format("{0}", reader[0]));
}
}
conn.Close();
}
And then return the initials List, and then in your GUI you could say:
comboBox1.DataSource = returnedList;
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;