C# Database Displaying Relevant Data in Textboxes - c#

I'm stuck with something and I'd appreciate it if anyone can assist me.
I have a simple MS Access database that's linked to my program. The first thing I did was fill a combobox with one of the fields in my database ("Product Description").
What I'd like to do is when a user selects an item in the combobox, all the other fields in the record be displayed in text boxes.
string sConnection;
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=XYZDatabase.accdb";
OleDbConnection dbConn;
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
cbxProducts.DisplayMember = "Product Description";
dbConn.Close();
I've considered using possibly SQL or a DataReader, though I'm really not sure.
This is the event where I want the textboxes to be filled. I'm literally stuck here.
private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
txtProductNumber.Text =
txtProductDescription.Text =
txtProductCategory.Text =
txtProductCost.Text =
}
I hope I haven't formatted my question wrong or anything, apologies if I have, this is my first time posting here! Dx

I wonder if your combo box is actually showing data from the DB.
In the first code block after
dbConn.Open()
and before
dbConn.Close()
you should have code like this:
SqlCommand sc = new SqlCommand("select prodid, proddesc from products", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("prodid", typeof(string));
dt.Columns.Add("proddesc", typeof(string));
dt.Load(reader);
cbxProducts.ValueMember = "prodid";
cbxProducts.DisplayMember = "proddesc";
cbxProducts.DataSource = dt;
And then in the second code block you need to fetch the selected Product ID first.
private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
string ID = comboBox1.SelectedValue.ToString();
//Based on ID make a sql query and fetch the details of that product from the DB.
//Follow the earlier code block to make DB connection and execute query.
//Then populate the data in individual text boxes by looping through the dr.
//I am leaving this deliberately for you to figure out and I am sure you can.
txtProductNumber.Text =
txtProductDescription.Text =
txtProductCategory.Text =
txtProductCost.Text =
}

Related

How can I populate a textbox with database values from a combobox?

I am quite new to C# and I am trying to populate fill several textboxes with data from a selected combobox.
I have my main window with the textboxes and comboboxes and a separate class for the connection to the database (I am using XAMPP/PhpMyAdmin).
I managed to fill the comboboxes with the data from the database, but I cannot fill the texboxes from the selected combobox.
I checked other questions and tutorials, but all I managed to achieve is to get the primary key into the text box, but I need different columns from the table, depending on the textbox.
I populated the combobox from the database:
void Completez_Combo_Furnizor()
{
combo_furnizor = DB_Furnizori.Combo_Furnizor();
comboBoxFurnizor.Items.Clear();
comboBoxFurnizor.DataSource = combo_furnizor;
comboBoxFurnizor.ValueMember = "id_furnizor";
comboBoxFurnizor.DisplayMember = "nume";
}
I double clicked on the combobox and wrote the following, but all I can get is the primary key (the first column). In the textbox, I need to get the 7th column (which is a double type.
private void comboBoxFurnizor_SelectedIndexChanged(object sender, EventArgs e)
{
textBoxPret.Text = comboBoxFurnizor.SelectedItem.ToString();
}
And this is from the database class (DB_Furnizori.cs), where I open the connection and have multiple queries for the database.
public static DataTable Combo_Furnizor()
{
conn.Open();
MySqlCommand comboFurnizor = new MySqlCommand("SELECT * from furnizori ORDER BY nume", conn);
MySqlDataAdapter adaptc = new MySqlDataAdapter(comboFurnizor);
DataTable combo_furnizori = new DataTable();
adaptc.Fill(combo_furnizori);
conn.Close();
return combo_furnizori;
}
Please help.
For your SelectedIndexChanged Method :
private void comboBoxFurnizor_SelectedIndexChanged(object sender, EventArgs e)
{
textBoxPret.Text = comboBoxFurnizor.SelectedItem.ToString();
}
You need to make another call to the database and retrieve the data you want using the values/Id (or whatever is the unique identifier) from the combobox. If you're trying to retrieve data on a selected index change you need to reference some type of data source for me I used a DataSet instead of DataTable (makes retrieving values in cells easier):
string StoredProc = "GetItemNotes";
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(StoredProc, conn);
SqlDataAdapter da = new SqlDataAdapter();
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(ds);
For populating the data within my Textbox I did this:
Notes.Text = ds.Tables[0].Rows[0]["Notes"].ToString();

c# how to access data fields of the selected in DataGridView database record

I'm new to the database programming, so I have probably very simple question.
On the form I have a DataGridView which shows all records from the SQL database, from single table. When I select a line (OnRowEnter event), I would like to display the same data in the textBoxes, which are not binded to the DataSource, but I do not know how to access the selected record and its fields.
I have seen many examples which use SQL statements, but is it the only way? Or is there a simpler method. I thought I should be able to access the current record and its fields almost directly? Is it possible?
I'm using Visual Studio Community 2013
Thx in advance for your help.
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
string asd = dataGridView1.Rows[e.RowIndex].Cells["NameOfColumn"].Value.ToString();
}
You can access any column of any row by this line.
EDIT:
You just told me you want to populate 2 textboxes from database and on buttons(save - overwrite) you want to save/overwrite it. So why you do not populate it from database
using (FbConnection con = new FbConnection(connectionString))
{
con.Open();
using (FbCommand cmd = new FbCommand("SELECT TEXT1, TEXT2 FROM TABLE WHERE CONDITION", con))
{
FbDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
}
con.close();
}
and then after user press save you just take whole text and update database
using (FbConnection con = new FbConnection(connectionString))
{
con.Open();
using (FbCommand cmd = new FbCoimmand("UPDATE TABLE SET TEXT1 = #Text1, TEXT2 = #Text2 WHERE CONDITION))
{
cmd.Parameters.AddWithValue("#Text1", textBox1.Text);
cmd.Parameters.AddWithValue("#Text2", textBox2.Text);
cmd.ExecuteNonQuery();
}
con.Close();
}
if user is writing text in some other textbox and you want to add that text to current text in database so you just read text from database and put it in string, on that string you add string from user and save like that to database

Updating DataGridView After row search result

I have a very basic question I want to update DataGridView using this code
private void updateDGV1_Click(object sender, EventArgs e)
{
SQLiteConnection sqliteCon = new SQLiteConnection(dbConnectionString);
// open connection to database
try
{
cmbl1 = new SQLiteCommandBuilder(datadp1);
datadp1.Update(ds1, "PlotDetails");
MessageBox.Show("Information Updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
load_table();
AutoCompleteSizeSearch();
AutoCompletePlotSearch();
AutoCompleteOwnerSearch();
AutoCompleteLocatoinSearch();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
After search for a result using this code
private void plots_txt_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(dt1);
dv.RowFilter = string.Format("D_ID LIKE '%{0}' AND Area LIKE '%{1}' AND Cat LIKE '%{2}' AND PBS LIKE '%{3}%' AND Name LIKE '%{4}%' AND Size LIKE '%{5}%' AND Location LIKE '%{6}%' AND PlotNo LIKE '%{7}%'", dids_combo.Text, areacs_txt.Text, categorycs_txt.Text, phblses_txt.Text, owners_txt.Text, sizes_txt.Text, locations_txt.Text, plots_txt.Text);
dataGridView1.DataSource = dv;
}
After getting result of search I couldn't been able to update searched result.
updateDGV1_Click works fine on the whole DGV but not on Searched result like in below image
After search,result not updating
I would actually recommend using the TableAdapter to communicate with your database instead of generating a connection in that fashion. This will also allow you to easily update your DataGridView with the contents of the TableAdpater Query (Search) that you want to preform. I wish I could go into more detail but I'm in a hurry at the moment I will provide links explaining this better below.
https://msdn.microsoft.com/en-us/library/bz9tthwx.aspx
I personally use TableAdapters to connect databases in my projects, but I have found a solution that may also allow you to keep your code the way it is for the most part.
http://www.codeproject.com/Articles/14249/How-to-populate-DataGridView-GridView-with-SQL-sta
What you will need to do when you want to preform a search on the current working DataSet. This code is an example I haven't tested it.
string conn_str = "Data Source=dbServer;Initial Catalog=testDB;Integrated Security=True";
string sql_str = “select * from table1”;
SqlDataAdapter data_adapter = new SqlDataAdapter(sql_str, conn_str);
SqlCommandBuilder cmd_builder = new SqlCommandBuilder(data_adapter);
// Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
// This line populates our new table with the data from our sql query
data_adapter.Fill(table);
db_binding_source.DataSource = table;
// Resize the DataGridView columns to fit the newly loaded content.
data_grid_view.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
// you can make it grid readonly.
data_grid_view.ReadOnly = true;
// finally bind the data to the grid
data_grid_view.DataSource = db_binding_source;
Here is also another answer on SO similar to what you're asking
How do I Update/Reload DataGridView BindingSource?

Editing contents of a listbox that is populated by a sql query datasource using c#

I have a list box that is populated by a query result set, i would to give the user the ability to edit the contents of the list box, and update the database back end, how can i achieve this?
public Brand_Manager(Main parent)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConn"].ConnectionString.ToString());
SqlCommand cmd = new SqlCommand("select Brand_ID, Brand_Name from Brand where status=1", conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable t = new DataTable();
da.Fill(t);
listBox1.DisplayMember = "Brand_Name";
listBox1.DataSource = t;
listBox1.ValueMember = "Brand_ID";
conn.Close();
}
private void Edit_Button_Click(object sender, EventArgs e)
{
this.Edit_Button.Enabled = false;
object item = listBox1.SelectedItem;
Edit_Brand frm = new Edit_Brand();
this.AddOwnedForm(frm);
frm.ShowDialog();
}
Do you use WPF or WinForms? Anyway you need to investigate Bindings: BindingSource in WinForms or Binding class in WPF (http://msdn.microsoft.com/en-us/library/ms750612.aspx).
Look at DataTable events http://msdn.microsoft.com/en-us/library/system.data.datatable_events.aspx . There is RowChangedEvent. Call update sql command in its handler.
You need to use datagridview for this purpose. It is designed for this purpose. You can assign the datasource to gridview and allow user to edit rows. Then by handling row edited event or by giving the button you can update the database. See an example here

saving form in database

I was wondering how could I retrieve the data from SQL server compact database that I just saved and insert it into textbox of newly created form. The source code is not complete, I just wanted to save space. Connection is fine, and I'm able to add data into database in the actual program. I just would like to know how to retrieve it and put it into textbox of newly created form. This is done in WinForms.Thank you!
public void b1_Click(object sender, EventArgs e)
{
SqlCeCommand command = new SqlCeCommand("INSERT INTO tbl1(Name) VALUES (#Name, #LastName)", conn);
command.Parameters.AddWithValue("#Name", t1.Text);
command.ExecuteNonQuery();
}
private void b2_Click(object sender, EventArgs e)
{
Form form2 = new Form();
form2.Show();
t3.Location = new System.Drawing.Point(0, 35);
t3.Size = new System.Drawing.Size(85, 15);
//access database and insert data into textbox
t3.Text = ?
form2.Controls.Add(t3);
}
Well it's not to hard to just get a value from the database, something like this should suit your needs:
SqlCeCommand command = new SqlCeCommand("SELECT * FROM tbl1(Name) WHERE name = #Name AND last_name = #LastName", conn);
command.Parameters.AddWithValue("#Name", "Hank");
command.Parameters.AddWithValue("#Name", "Hill");
SqlDataReader reader = command.ExecuteReader();
t1.Text = reader.GetString(0);
t2.Text = reader.GetString(1);
When in doubt, start at the official docs. See this sample, on msdn: http://msdn.microsoft.com/en-us/library/aa226134(v=sql.80).aspx
They show there a couple of SQL commands like SELECT, INSERT and UPDATE. You know how to insert, so you are now interested in the SELECT part. See how they use data reader and try that for starters.
Here is an example:
http://msdn.microsoft.com/en-us/library/aa983340(v=VS.80).aspx
Please also check codeplex.com for additional examples/projects

Categories

Resources