How to Display data in textbox using MS Access database - c#

Im trying to display user data from database into textbox, so that user can edit/update that data later.
Im getting error of no value has been set for at least one of the required parameters.
I did not write the SELECT * FROM, because i'm not displaying data like AdminRights.
Can you please help me fix the error?
This is my code
private void refresh_Click(object sender, RoutedEventArgs e)
{
if (!isPostBack)
{
DataTable dt = new DataTable();
con.Open();
OleDbDataReader dr = null;
OleDbCommand cmd = new OleDbCommand("SELECT [Name], [LastName], [UserName], [Password], [Address], [Email] FROM User WHERE [ID] = ?", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
name.Text = (dr["Name"].ToString());
lName.Text = (dr["LastName"].ToString());
uName.Text = (dr["UserName"].ToString());
pass.Text = (dr["Password"].ToString());
address.Text = (dr["Address"].ToString());
email.Text = (dr["Email"].ToString());
id.Text = (dr["ID"].ToString());
}
con.Close();
}
}

.....FROM User WHERE [ID] = ?", con);
The ? placeholder requires a parameter defined in the command parameters collection.
So, before calling ExecuteReader you need to add the parameter for the ID field
cmd.Parameters.AddWithValue("#p1", ????value for the ID field);
dr = cmd.ExecuteReader();
If you want to retrieve a single record from your table you need to know the value for the field that uniquely identifies the records in your table.
To get that value it is necessary to understand how do you reach this code. If you select a row from a list, grid or combo, probably you have loaded that control with your user names and their ID.

String id = idTextBox.Text;
OleDbCommand command = new OleDbCommand("Select *from User Where [ID]= "+ id +" ");
command.Connection = conn;
OleDbDataReader dr = null;
conn.Open();
dr = command.ExecuteReader();
while (dr.Read())
{
name.Text = (dr["Name"].ToString());
lName.Text = (dr["LastName"].ToString());
uName.Text = (dr["UserName"].ToString());
pass.Text = (dr["Password"].ToString());
address.Text = (dr["Address"].ToString());
email.Text = (dr["Email"].ToString());
id.Text = (dr["ID"].ToString());
}
conn.Close();
this will work fine change lines and execute

Related

Insert into mysql tables

I'm trying to insert some records to 2 tables at same event
private void Btngravar_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("server=localhost;user id=root;database=saude;Password=");
conn.Open();
MySqlCommand objcmd = new MySqlCommand("insert into dispensacao (DESTINATARIO,COD_UNIDADE,COD_DEPARTAMENTO,DATA,SOLICITANTE,DEFERIDO_POR) values(?,?,?,?,?,?)", conn);
objcmd.Parameters.Add("#DESTINATARIO", MySqlDbType.VarChar, 45).Value = Cmbdestinatario.Text;
objcmd.Parameters.AddWithValue("#COD_UNIDADE", string.IsNullOrEmpty(Txtcodigounidade.Text) ? (object)DBNull.Value : Txtcodigounidade.Text);
objcmd.Parameters.AddWithValue("#COD_DEPARTAMENTO", string.IsNullOrEmpty(Txtcodigodep.Text) ? (object)DBNull.Value : Txtcodigodep.Text);
DateTime fdate = DateTime.Parse(Txtdata.Text);
objcmd.Parameters.Add("#DATA", MySqlDbType.DateTime).Value = fdate;
objcmd.Parameters.Add("#SOLICITANTE", MySqlDbType.VarChar, 45).Value = Txtsolicitante.Text;
objcmd.Parameters.Add("#DEFERIDO_POR", MySqlDbType.VarChar, 45).Value = Txtdeferido.Text;
objcmd.ExecuteNonQuery();
conn.Close();
conn.Open();
objcmd = new MySqlCommand("insert into produtos_disp(COD_DISPENSACAO,COD_PRODUTO,PRODUTO,QUANTIDADE) values (?,?,?,?)", conn);
string selectid = "select ifnull (max(ID),1) from dispensacao";
objcmd = new MySqlCommand(selectid, conn);
MySqlDataReader reader = objcmd.ExecuteReader();
if (reader.Read())
{
Txtcodigo.Text = reader.GetString("ID");
}
//Txtcodigo.DataBindings.Add("Text", dtid, "ID");
objcmd.Parameters.AddWithValue("#COD_DISPENSACAO", Txtcodigo.Text);
objcmd.Parameters.AddWithValue("#COD_PRODUTO", dtproddisp.Rows[0][0]);
objcmd.Parameters.AddWithValue("#PRODUTO", dtproddisp.Rows[0][1]);
objcmd.Parameters.AddWithValue("#PRODUTO", dtproddisp.Rows[0][2]);
Code from the comment
string selectQuery = "SELECT * from departamento";
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
DataTable dt2 = new DataTable();
dt2.Load(reader);
Cmbdestinatario.DisplayMember = "nome";
Cmbdestinatario.ValueMember = "CODIGO";
Cmbdestinatario.DataSource = dt2;
Txtcodigodep.DataBindings.Add("Text", dt2, "CODIGO");
The first part is working, I can see records inserted on dispensacao table, but the second isn't working, error:
Could not find specified column in results: ID
and I need to get products from datagridview,
App screen:
MySQL Dispensacao table:
My problem now is inserting those selected products from datagridview on database and get the id from dispensacao to insert on products table,
If you want to insert more rows in a database(from what I known), you should add a checkbox in a DataGridView Column and store checked rows to a list. Then you should use a for loop to insert each data to Database by list values.
If you want the code please comment me.

Retrieve database data linked to PersonID and show in listbox

So i've created a application that is linked to a MS Acces database. I have a login system and when the login is succesful, their Personal data is displayed in some textboxes. One of these textboxes shows their PersonID (the ID for acces database).
User can make a appointment. This will be written in the database under UserID - Appointment date - Treatment. I want to retrieve this info and shows it into my listbox. But don't know why, because it needs to only retrieve the data that is linked to the logged in UserID ofcourse.
I have something like this but i'm stuck right now.
connection.Open();
OleDbCommand command = new OleDbCommand();
string afspraken = "select * from Appointments where PersonID = '" + textBox4.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
listBox2.DataSource = reader;
connection.Close();
DataTable dt = new DataTable();
OleDbCommand command = new OleDbCommand();
string afspraken = "select * from Appointments where PersonID = '" + textBox4.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
dt.Load(reader);
foreach (DataRow Dr in dt.Rows)
{
listBox1.Items.Add(Dr["COLUMNNAME"].ToString());
}
con.Close();
Try This ...

An OleDbParameter with ParameterName "" is not contained by this OleDbParameterCollection

I keep getting a parameter name error? at the bottom I have attached an image to help explain the problem.
private void loadProgress(string jobNumber)
{
productioninfo.Open();
OleDbCommand _contractReview = new OleDbCommand ("SELECT [Contract Review] FROM [Main$] WHERE [Job No] = '#Job No'", productioninfo);
_contractReview.Parameters.Add("#Job No", OleDbType.Char);
_contractReview.Parameters["Job No"].Value = jobNumber;
OleDbDataReader dr = _contractReview.ExecuteReader();
while (dr.Read())
{
}
dr.Close();
}
Try like this;
OleDbCommand _contractReview = new OleDbCommand ("SELECT [Contract Review] FROM [Main$] WHERE [Job No] = #JobNo", productioninfo);
_contractReview.Parameters.Add("#JobNo", OleDbType.Char);
_contractReview.Parameters["JobNo"].Value = jobNumber;
And don't use spaces in your table and column names. It is not recommended.
Check out Database, Table and Column Naming Conventions?

How to get a value in another table, store it in a variable or data reader, and then use it to update another table

does anyone know how do I get the StudentID from Students table, store it in datareader or dataset, and then use it to update another table, which is Users Table, because I want the username and password of users would be their StudentID as a default. BTW, this is C# ASP.NET.
Here is my code.
SqlConnection conUpdate = new SqlConnection(GetConnectionString());
conUpdate.Open();
SqlCommand com2 = new SqlCommand();
com2.Connection = conUpdate;
com2.CommandText = "SELECT Students.StudentID, Users.UserID FROM Students, Users " +
"WHERE Students.UserID = Users.UserID";
int UserId = ((int)com2.ExecuteScalar());
com2.CommandText = "SELECT MAX(StudentID) FROM Students";
int StudentId = ((int)com2.ExecuteScalar());
com2.CommandType = CommandType.Text;
com2.CommandText = "UPDATE Users SET UserName=#UserName, Password=#Password WHERE UserID=#UserID";
com2.Parameters.Add("#UserName", SqlDbType.NVarChar);
com2.Parameters.Add("#Password", SqlDbType.NVarChar);
com2.Parameters[0].Value = reader;
com2.Parameters[1].Value = reader;
com2.ExecuteNonQuery();
conUpdate.Close();
conUpdate.Dispose();
Since you already getting UserId in your select query, you should get the value using DataReader. like this:
// Execute the query
SqlDataReader rdr = cmd.ExecuteReader();
int UserId;
while(rdr.Read())
{
UserId = Convert.ToInt32(rdr["UserID"].ToString());
}
Your command com2.CommandText = "SELECT MAX(StudentID) FROM Students"; will return the Max student ID, and that is probably not needed. Your earlier command com2.CommandText = "SELECT Students.StudentID, Users.UserID .... is what you need to get the student UserID.
You can use Data reader (Connection oriented) like below:
SqlDataReader reader = com2.ExecuteReader();
while (reader.Read())
{
int UserId = Convert.ToInt(reader[0]);// or reader["UserID"]
}
reader.Close();
Or you can use DataAdapter (disconnected mode) like:
SqlDataAdapter a = new SqlDataAdapter(com2, connection);
DataTable dt = new DataTable();
a.Fill(dt);
Now your dt.Rows["UserID"] will have the UserID you need.
You may wanna see this: http://www.dotnetperls.com/sqldataadapter
If I understood you correctly, I think the following code might work. Or in the least give you an idea about how you can go about it. Am assuming that you want each student's UserName and Password to default to their StudentID
SqlConnection conUpdate = new SqlConnection(GetConnectionString());
conUpdate.Open();
SqlCommand com2 = new SqlCommand();
com2.Connection = conUpdate;
com2.CommandType = CommandType.Text;
com2.CommandText = "SELECT Students.StudentID, Users.UserID FROM Students, Users " +
"WHERE Students.UserID = Users.UserID";
SqlDataReader reader = com2.ExecuteReader();
if(reader != null)
{
while(reader.Read())
{
SqlCommand com3 = new SqlCommand();
com3.Connection = conUpdate;
com3.CommandType = CommandType.Text;
com3.CommandText = "UPDATE Users SET UserName=#UserName, Password=#Password WHERE UserID=#UserID";
// Assuming that you need both the UserName and Password to default to StudentID
com3.Parameters.AddWithValue("#UserName", reader.GetString(0)); // Assuming StudentID is NVARCHAR
com3.Parameters.AddWithValue("#Password", reader.GetString(0)); // Assuming StudentID is NVARCHAR
com3.Parameters.AddWithValue("#UserID", reader.GetString(1)); // Assuming UserID is NVARCHAR
com3.ExecuteNonQuery();
}
reader.Close();
}
conUpdate.Close();

C# drop downlist values not insert

i have written a code to load the data to drop down list, as i written it was loaded, but while trying to insert the value of drop down list, (i mean selectedItem.text) it will not insert, instead if thtat selectedIndex=0 alone has been inserted. please correct me.
//Load the name to Drop down list
public void name()
{
DropDownList1.Items.Clear();
ListItem i = new ListItem();
i.Text = "-Select-";
DropDownList1.Items.Add(i);
DropDownList1.SelectedIndex = 0;
Conhr.Open();
string s;
s = "select EmployeeName from tbl_EmploeeDetails where SiteName='" + Label5.Text + "' ";
SqlCommand cd = new SqlCommand(s, Conhr);
SqlDataReader dr;
dr = cd.ExecuteReader();
while (dr.Read())
{
ListItem m= new ListItem();
m.Text = dr["EmployeeName"].ToString().Trim();
DropDownList1.Items.Add(m);
}
dr.Close();
Conhr.Close();
}
//trying to insert the data for drop down list
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
string a;
a = "insert into tbl_KKSUser(EName,Uname,Password)values(#en,#un,#pas)";
SqlCommand cm = new SqlCommand(a, con);
SqlParameter paramName;
paramName = new SqlParameter("#en", SqlDbType.VarChar, 25);
paramName.Value = DropDownList1.SelectedItem.Text;
cm.Parameters.Add(paramName);
cm.ExecuteNonQuery();
con.close
}
answer will be like this in data base
1 -Select- dsad AGEAcwBkAGY=
2 -Select- da AGEAZA==
Every time we are working with DropDownlist the best approach is selectedvalue,
Try to use:
Set the DataSource to the reader and execute DataBind()
conn.Open();
SqlDataReader MyDataSet = cmd.ExecuteReader();
ddlClassList.DataSource = MyDataSet;
ddlClassList.DataTextField = "Field1";
ddlClassList.DataValueField = "Field2";
ddlClassList.DataBind();
MyDataSet.Close();
conn.Close();

Categories