Fetch data in database always display first record - c#

When i search differennt building number in search box it always display first record in the table.
When i tried diffrent building number it does now display it always stay first record of the table.
Can anybody correct my code. Thanks.
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection con2 = new OleDbConnection(#"provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\test\TDB.accdb");
try
{
con2.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con2;
string query = "select * from TestDatabase where Building_No='" + textBox1.Text + "'";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Building_No", textBox1.Text);
cmd.Parameters.AddWithValue("#Building_Name", textBox4.Text);
cmd.Parameters.AddWithValue("#Year_", textBox2.Text);
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox4.Text = reader["Building_Name"].ToString();
textBox2.Text = reader["Year_"].ToString();
}
}
catch (Exception)
{
MessageBox.Show("No Reference # found!", "Error");
textBox4.Clear();
textBox2.Clear();
}
}

If the result of 'OleDbCommand.ExecuteReader' is multiple rows
You must call OleDbDataReader.Read() multiple.
example:
while (reader.Read())
{
Console.WriteLine(reader["Building_Name"].ToString());
}
e.g.
textBox4.Text = "";
while (reader.Read())
{
textBox4.Text += reader["Building_Name"].ToString() + ",";
}

It could be because you didn't close the connections. Can you try the code below?
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection con2 = new OleDbConnection(#"provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\test\TDB.accdb");
try
{
con2.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con2;
string query = "select * from TestDatabase where Building_No='" + textBox1.Text + "'";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Building_No", textBox1.Text);
cmd.Parameters.AddWithValue("#Building_Name", textBox4.Text);
cmd.Parameters.AddWithValue("#Year_", textBox2.Text);
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox4.Text = reader["Building_Name"].ToString();
textBox2.Text = reader["Year_"].ToString();
}
reader.Close();
cmd.Dispose();
con2.Close();
}
catch (Exception)
{
MessageBox.Show("No Reference # found!", "Error");
textBox4.Clear();
textBox2.Clear();
}
}

Related

Binding a Date to TextBox in Textmode=Date

I have an update panel with some gridviews being populated on postback as well as some textboxes that are populated through code and an SqlDataReader on _SelectedIndexChanged. Everything is working except for the two date textboxes that are set to TextMode=Date are not populating. I'm sure it's some formatting issue and I've searched and tried a few different things to no avail..... Thanks in advance !
P.s. edited out connection string
public void ddlSO_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = "";
String strQuery = "select strServiceOrderNo, strCustomerNo, strCustomerName, strCustomerAddress1, strCustomerAddress2, strCustomerAddress3, strServiceRequestDate, strServiceOrderDate, intStatusCodeID, intRepID from TServiceOrders where" +
" intServiceOrderID = #intServiceOrderID";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#intServiceOrderID", ddlSO.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
txtCUSTNO.Text = sdr["strCustomerNo"].ToString();
txtSONO.Text = sdr["strServiceOrderNo"].ToString();
txtAddress1.Text = sdr["strCustomerAddress1"].ToString();
txtAddress2.Text = sdr["strCustomerAddress2"].ToString();
txtAddress3.Text = sdr["strCustomerAddress3"].ToString();
txtDateCreated.Text = sdr["strServiceOrderDate"].ToString() ;
txtDateDue.Text = sdr["strServiceRequestDate"].ToString();
txtCustName.Text = sdr["strCustomerName"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}

Search Data from combobox and textbox. How to load data into datagridview after executenotquery()

Now I have a combobox i choose "Name" and input some text. I have query data from my database. but now i don't know how to load data into datagridview.
This is my code button Search:
private void btnSearch_Click(object sender, EventArgs e)
{
String strSearch = txtSearch.Text.Trim();
String Selected = cbSearch.GetItemText(cbSearch.SelectedItem);
switch (Selected)
{
case "All Search":
LoadData();
break;
case "Name":
try
{
if (conn.State == ConnectionState.Open)
conn.Close();
MySqlCommand cmd = new MySqlCommand("Select * FROM sinhvien where name LIKE #name");
cmd.Connection = conn;
cmd.Connection.Open();
cmd.Parameters.Add(new MySqlParameter("#name", "%" + txtSearch.Text + "%"));
cmd.ExecuteNonQuery();***//I dont't know what to do after query here***
MessageBox.Show("Delete this row successfully!\n",
"Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (MySqlException)
{
MessageBox.Show("Error load data from database!","Notification", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
break;
break;
}
}
then how to load data from database into datagridview:
private void LoadData()
{
try
{
conn = new MySqlConnection(connString);
if (conn.State == ConnectionState.Open)
conn.Close();
daSinhVien = new MySqlDataAdapter("SELECT * FROM sinhvien", conn);
dtSinhVien = new DataTable();
dtSinhVien.Clear();
daSinhVien.Fill(dtSinhVien);
dgvSinhVien.DataSource = dtSinhVien;
}
catch (MySqlException)
{
MessageBox.Show("Can't not load data from sinhvien!!","Notification",MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
cbSearch.Items.Add("All Search");
cbSearch.Items.Add("Name");
cbSearch.Items.Add("Age");
cbSearch.Items.Add("Class");
cbSearch.Items.Add("Address");
}
Why are you using cmd.ExecuteNonQuery();?
That's for executing statements that you don't expect to have data returning - like a command that adjusts some records.
Instead, you might be looking for something like:
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
... this is off the MSDN page: https://msdn.microsoft.com/en-us/library/fksx3b4f.aspx

Retrieve Database values and show them on form using SQLDataReader

I am trying to retrieve data from a Database and show them on a form; but my code isn't working... I've got no errors, and logically it seems to work (to me) so I cannot figure out where I have gone wrong. That's where I need your help!
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
The 'tableListBox' is populated with all the values in column 'Default_Name'. I want it so that when the 'Default_Name' is selected from the list box it shows the values, in textboxes and comboboxes, that correspond with that row in the Database.
Any and all help would be appreciated. Thanks.
I'm going to start by changing your design a bit and suggest that perhaps you look at using a datatable and then just retrieving the rows from the datatable.
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
private DataTable dataTable;
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
foreach(DataRow row in dataTable.Rows)
{
textBox1.Text = row[2].ToString();
comboBox1.Text = row[3].ToString();
comboBox3.Text = row[4].ToString();
textBox2.Text = row[6].ToString();
comboBox2.Text = row[7].ToString();
comboBox4.Text = row[8].ToString();
}
da.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
I generally find that DataTables are more reliable than looping through the actual reader. Ofcourse this assumes that there is data being returned. Also try changing your select statement to this
string Query = "SELECT * FROM [Table]"
If that works, then the problem could be
There is no default name of the specified value or
tableListBox.SelectedValue is not returning any value, in which case, have a look at your listbox selected value
Thanks to Takarii for helping. I figured out who to make it work.
private void tableListBox_SelectedValueChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE ID = '" + tableListBox.SelectedIndex.ToString() + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
First I changed the void to 'SelectedValueChanged' and then I changed the 'WHERE' in the connection Query to the Row Index associated with the selected Value.
Thanks for everyone's help!

The error says "The ConnectionString property has not been initialized" in c#

this code is for the combo box where i want to select some index to show it to my textboxes.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
cmd.Connection = conn;
string query = "SELECT * FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'";
db.connectDB();
db.da.SelectCommand = new OleDbCommand(query, db.conn);
db.executeQryCommand(query, false);
maxRecord = db.ds.Tables[0].Rows.Count;
loadRecords(recordCounter);
cmd.CommandText = query;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["Gname"].ToString();
textBox2.Text = dr["Gcontactno"].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}
//My program is completely running but not in this section. :(
Is you made an connection between your application and database source using conn object ? You might be used conn object as a connection object but before this was you initialized you Connection ?
Simpy use like
"SqlConnection conn=new SqlConnection("Connection_Source");"
here is your error.
You have to define the connection string for the connection, here i suggest you one best method for executing command.
using (OleDbConnection conn = new OleDbConnection("yourconnectionString"))
{
conn.Open();
using (OleDbCommand cmd =new OleDbCommand("your query text", conn))
{
// execute your command
}
}
If its just to select value from comboBox and display in textBox , then below code will help you...
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT Gname,Gcontactno FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}

Trying to get database entries limited to current UserName

I have the database updating with the UserName of the person who uploaded a file and am trying to retrieve only the files the current user uploaded, to display in the gridview.
The page displays the current user name and when that person uploads a file everything is fine. Though when that user hits the search button, all records show up and I get the error:
Error:Invalid column name 'test'
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlDataReader reader;
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM UserUpload WHERE UserName = #un";
command.Parameters.Add(new SqlParameter("#un", UN));
command.Connection = conn;
conn.Open();
reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}
Change this line
string UserSearch = "SELECT * FROM UserUpload WHERE UserName =" + UN;
to
string UserSearch = string.Format("SELECT * FROM UserUpload WHERE UserName ='{0}'",UN);
you want to match to username as string strings are being wrapped in '' in SQL
If you would be matching by number it would work fine as numbers do not have this requirement.
UPDATE to UPDATE:
Change to something like this (untested)
SqlCommand com = new SqlCommand(UserSearch, conn);
{ DataSet ds = com.ExecuteReader();
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
conn.Close();
}
You would benefit from reading this
Use Parameters instead of assinging the Value to the query string
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString(); ;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string UserSearch = "SELECT * FROM UserUpload WHERE UserName = #un";
SqlCommand com = new SqlCommand(UserSearch, conn);
com.Parameters.Add(new SqlParameter("#un", UN));
com.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}

Categories

Resources