Data in not displayed on checkbox in C# & SQL Server - c#

I am trying to display the values from database. The textbox values are displayed successfully but checkbox values are not displayed, and it shows the error. I get the error shown in this screenshot:
Error Message
My code:
sql = "select * from repair where repairid = '" + repairid + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dread;
con.Open();
dread = cmd.ExecuteReader();
while (dread.Read())
{
checkBox7.CheckState = dread[6].ToString();
}

if(dread[6].ToString = = "True")
{
CheckBox7.Checked = "true";
}
else
{
CheckBox7.Checked = "false";
}

Related

How to get the value of my label? i am using c#

I have this c# form program and i want to get my text label value for some reasons, can somebody help?
I already tried this
String name = myLabel.Text
String name = myLabel.Text.ToString
but it will display none.
conn = dbHelper.getConnect();
conn.Open();
cmd = new SqlCommand("select custID from customer where name = '" + custNameLbl /*this is where i want to get the value*/ + "'", conn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
custIDStorage = Convert.ToInt32(dr[0].ToString()); //this is an int
namename.Text = custIDStorage.ToString(); //this is a label
}
cmd.Dispose();
dr.Close();
conn.Close();

Populating textbox from after selecting value from comboBox

I am trying to populate my textbox after selecting a value from my comboBox.
My code is running fine, I don't have any errors when I run it but when I select a value from my comboBox, it's not populating my textbox. See my code below.
private OleDbConnection connection = new OleDbConnection();
public Form1()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ASUS\Documents\appointment2.accdb";
}
private void Lastname_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string query = "select * from appointments where patientNo = '" + Lastname.Text + "' ";
command.CommandText = query;
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
Two immediate issues that I see:
You are populating the CommandText property of the OleDbCommand object after issuing the ExecuteReader method, meaning there is no SQL statement being evaluated.
The SQL statement should be populated before the ExecuteReader method is issued, i.e.:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from appointments where patientNo = '" + Lastname.Text + "' ";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();
The where clause of your SQL statement assumes that patientNo contains string data, which could be incorrect given the name of this field.
Just found out the issue. Had the wrong value to compare my Lastname.Text with and fixed the code's arrangement. Thanks for all your help everyone.
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from appointments where lastName = '" + Lastname.Text + "' ";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();

Updating records in SQL Server database using ASP.NET

I am new to ASP.NET, I am facing some difficulty in updating records inside database in ASP.NET. My code is showing no errors, but still the records are not being updated. I am using SQL Server 2012.
Code behind is as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] != null)
{
con.Open();
string query = "Select * from Customers where UserName ='" + Session["user"] + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
txt_name.Text = reader["CustName"].ToString();
txt_phonenumber.Text = reader["Contact"].ToString();
txt_address.Text = reader["CustAddress"].ToString();
txt_cardnum.Text = reader["CustAccountNo"].ToString();
txt_city.Text = reader["CustCity"].ToString();
txt_emailaddress.Text = reader["Email"].ToString();
txt_postalcode.Text = reader["CustPOBox"].ToString();
Cnic.Text = reader["CustCNIC"].ToString();
}
con.Close();
}
else
{
Response.Redirect("Login.aspx");
}
}
protected void BtnSubmit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd2 = con.CreateCommand();
SqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "Select CustID from Customers where UserName = '" + Session["user"] + "'";
int id = Convert.ToInt32(cmd1.ExecuteScalar());
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "update Customers set CustName='" + txt_name.Text + "',CustCNIC='" + Cnic.Text + "',Email='" + txt_emailaddress.Text + "',CustAccountNo='" + txt_cardnum.Text + "',CustAddress='" + txt_address.Text + "',CustPOBox='" + txt_postalcode.Text + "' where CustID='" + id + "'";
cmd2.ExecuteNonQuery();
con.Close();
}
Help will be much appreciated. THANKS!
After debugging the result i am getting is this
cmd2.CommandText "update Customers set CustName='Umer Farooq',CustCNIC='42101555555555',Email='adada#gmail.com',CustAccountNo='0',CustAddress='',CustPOBox='0' where CustID='6'" string
Here Account Number And POBOX is 0 and address is going as empty string. But i have filled the text fields
First thing to do to fix this is to use good ADO techniques, using SqlParameters for the passed in values; and not the risky SQL Injection method of concatenating strings together.
This first portion does just that. I have added in the int sqlRA variable to read the results of the non-query, which will return Rows Affected by the query. This is wrapped in a simple try...catch routine to set the value to negative 1 on any error. Other error handling is up to you. That makes your code look something like this:
cmd1.Parameters.AddWithValue("#SessionUser", Session["User"]);
int id = Convert.ToInt32(cmd1.ExecuteScalar());
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "UPDATE Customers SET CustName = #CustName, CustCNIC = #CustCNIC, Email = #Email, CustAccountNo = #CustAccountNo, CustAddress = #CustAddress, CustPOBox = #CustPOBox WHERE (CustID = #CustID)";
cmd2.Parameters.AddWithValue("#CustName", txt_name.Text);
cmd2.Parameters.AddWithValue("#CustCNIC", Cnic.Text);
cmd2.Parameters.AddWithValue("#Email", txt_emailaddress.Text);
cmd2.Parameters.AddWithValue("#CustAccountNo", txt_cardnum.Text);
cmd2.Parameters.AddWithValue("#CustAddress", txt_address.Text);
cmd2.Parameters.AddWithValue("#CustPOBox", txt_postalcode.Text);
cmd2.Parameters.AddWithValue("#CustID", id);
int sqlRA
try { sqlRA = cmd2.ExecuteNonQuery(); }
catch (Exception ex) {
sqlRA = -1;
// your error handling
}
/* sqlRA values explained
-1 : Error occurred
0 : Record not found
1 : 1 Record updated
>1 :Multiple records updated
*/
Now reading through your code, all we are doing with the first query is mapping the Session["User"] to id, and then using that id in the second query to do the update, and that Username is not updated in the second. Waste of a query most likely, as we could use the Session["User"] to do the update. That will bring you down to this query, and still bring back that Rows Affected value back:
cmd0.CommandType = CommandType.Text;
cmd0.CommandText = "UPDATE Customers SET CustName = #CustName, CustCNIC = #CustCNIC, Email = #Email, CustAccountNo = #CustAccountNo, CustAddress = #CustAddress, CustPOBox = #CustPOBox WHERE (UserName = #SessionUser)";
cmd0.Parameters.AddWithValue("#CustName", txt_name.Text);
cmd0.Parameters.AddWithValue("#CustCNIC", Cnic.Text);
cmd0.Parameters.AddWithValue("#Email", txt_emailaddress.Text);
cmd0.Parameters.AddWithValue("#CustAccountNo", txt_cardnum.Text);
cmd0.Parameters.AddWithValue("#CustAddress", txt_address.Text);
cmd0.Parameters.AddWithValue("#CustPOBox", txt_postalcode.Text);
cmd0.Parameters.AddWithValue("#SessionUser", Session["User"]);
int sqlRA
try { sqlRA = cmd0.ExecuteNonQuery(); }
catch (Exception ex) {
sqlRA = -1;
// your error handling
}
/* sqlRA values explained
-1 : Error occurred
0 : Record not found
1 : 1 Record updated
>1 :Multiple records updated
*/
When BtnSubmit fires the event, the code in the Page_Load runs before the codes in BtnSubmit, replacing the values placed in the TextBox with the values from the Database before the Update takes place.

How to Display data in textbox using MS Access database

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

how to fill textbox from dataset?

i run this and i want to fill textbox txtFname with data - but it dont do nothing
using (Conn = new SqlConnection(Conect))
{
Conn.Open();
SQL = "SELECT * FROM MEN where id = '" + txtBAR.Text.Trim() + "'";
dsView = new DataSet();
adp = new SqlDataAdapter(SQL, Conn);
adp.Fill(dsView, "MEN");
adp.Dispose();
txtFname.Text = dsView.Tables[0].Rows[3][0].ToString();
txtFname.DataBind();
Conn.Close();
}
how to do it ?
thank's in advance
using (Conn = new SqlConnection(Conect)) {
try {
// Attempt to open data connection
Conn.Open();
// Compose SQL query
string SQL = string.Format("SELECT * FROM MEN WHERE id = '{0}'", txtBAR.Text.Trim());
using(SqlCommand command = new SqlCommand(SQL,Conn)) {
// Execute query and retrieve buffered results, then close connection when reader
// is closed
using(SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection)) {
// Assign txtFname value to search value and clear value if no results returned
txtFname.Text = reader.Read() ? reader[0].ToString() : string.Empty;
reader.Close();
}
}
}
finally {
// Regardless of whether a SQL error occurred, ensure that the data connection closes
if (Conn.State != ConnectionState.Closed) {
Conn.Close();
}
}
}
However, I would advise that you
update your SQL query to return the
actual column names instead of *
replace reader[0].ToString() with
reader["FirstName"].ToString()
using (Conn = new SqlConnection(Conect))
{
Conn.Open();
SQL = "SELECT * FROM MEN where id = '" + txtBAR.Text.Trim() + "'";
SqlCommand command= new SqlCommand(SQL,Conn);
SqlDataReader reader = command.ExecuteReader()
reader.Read();
//Call Read to move to next record returned by SQL
//OR call --While(reader.Read())
txtFname.Text = reader[0].ToString();
reader.Close();
Conn.Close();
}
Edit: I just noticed 'dataSet' not database, anyway you are reading third row, is your query returns more than one row?

Categories