Populate textbox with selected items from database - c#

private void fillProduct() {
SqlConnection conn = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
conn.Open();
string query = "Select prodID from product";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0) {
cmbPCode.DataSource = dt;
cmbPCode.DisplayMember = "prodID";
cmbPCode.ValueMember = "prodID";
}
private void cmbPCode_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
con.Open();
string query = "Select * from product where prodID = '"+cmbPCode.Text+"'".ToString();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
tbdc.Text = dr["prodDescription"].ToString();
}
}
i am having trouble with getting my items from the database according to the selected index i get this error
Conversion failed when converting the varchar value
'System.Data.DataRowView' to data type int
can someone please help me how to convert SqlDataReader to String. because i notice that when i retrieve a column with varchar/string datatype i am not having this kind error but if i retrieve a column with int datatype i get this error.

Replace This:
string query = "Select * from product where prodID = '"+cmbPCode.Text+
"'".ToString();
With This:
string query = "Select * from product where prodID = "+cmbPCode.Text;
Suggestion: Your query is open to SQL Injection i would suggest you to use parameterised queries to avoid them.
Using Parameterised Queries:
string query = "Select * from product where prodID = #ID";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID",cmbPCode.Text);

Related

get data from database and display it in gridview (asp.net)

I have a database (SQL server) and I added it into my webpage project but the problem is I cannot display the data in a gridview.
Here is my code:
string query;
SqlCommand SqlCommand;
SqlDataReader reader;
int sindex=DropDownList1.SelectedIndex+1;
int hindex =DropDownList3.SelectedIndex+1;
SqlDataAdapter adapter = new SqlDataAdapter();
//Open the connection to db
conn.Open();
query = string.Format("select * from table where clumn='"+s+"' ", s);
SqlCommand = new SqlCommand(query, conn);
adapter.SelectCommand = new SqlCommand(query, conn);
reader = SqlCommand.ExecuteReader();
GridView2.DataSource = reader;
GridView2.DataBind();
Change this
query = string.Format("select * from table where clumn='"+s+"' ", s);
to this
query = string.Format("select * from table where clumn='{0}' ", s);
Use SqlParameters instead of manipulating a string as you are doing now.
Also, use using statement to dispose objects correctly.
Don't use select * because it will affect performance, only select the columns needed.
Here an example of your code, modified:
using (SqlConnection conn = new SqlConnection(yourConnectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = "select column, column2 from table where column=#column";
command.Parameters.Add(new SqlParameter("column", SqlDbType.VarChar, 50));
command.Parameters["column"].Value = yourColumnValue;
conn.Open();
using (SqlDataReader sdr = sco.ExecuteReader())
{
GridView2.DataSource = sdr;
GridView2.DataBind();
}
}
better use SqlDatadapter:
DataTable dt = new DataTable();
...
using (SqlDataAdapter a = new SqlDataAdapter( new SqlCommand(query, conn)))
{
GridView2.DataSource =a.Fill(dt).AsDataView();
}

Conversion failed when converting the varchar value 'System.Data.DataRowView' to data type int

I always get the following error once I retrieved records with integer data type from my database using my combobox:
Conversion failed when converting the varchar value 'System.Data.DataRowView' to data type int.
It works when I replace my query and retrieve records that has varchar data type.
Can someone please help me how to modify my code to get the expected output?
Here is my code:
public void fillSupplier()
{
SqlConnection conn = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
conn.Open();
string query = "Select supID from Supplier";
SqlCommand cmd= new SqlCommand(query,conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0) {
cmbSupp.DataSource = dt;
cmbSupp.DisplayMember = "supID";
cmbSupp.ValueMember = "supID";
}
}
private void cmbSupp_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
conn.Open();
this.Refresh();
string query = "Select * from Supplier where supID='"+cmbSupp.Text+"'";
SqlCommand cmd = new SqlCommand(query,conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
tbsName.Text = dr["supName"].ToString();
tbsContact.Text = dr["supLocation"].ToString();
tbsLoc.Text = dr["supContact"].ToString();
}
}
Replace it with this (removed the single apostrophes, which indicate a string literal):
string query = "Select * from Supplier where supID = " + cmbSupp.Text;
Also, look into parameterizing your query. You'll be far less likely to run into issues like this, especially when the query you're executing has many parameters.
string query = "Select * from Supplier where supID = #supID";
...
cmd.Parameters.AddWithValue("#supID", int.Parse(cmbSupp.Text));
Here's some good reading material, with examples.

SQL update command not working

I have created a web page in Asp.net website. The following page load will run as it gets arguments from previous page. The page also has an option for editing the contents and updating in database. But when the button(save) is clicked it doesn't update the database.Kindly help in this. But when there is no connection in page load the update command works.
protected void Page_Load(object sender, EventArgs e)
{
String cust=Request.QueryString["custName"];
String env = Request.QueryString["env"];
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
view();
if (env == "Production")
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value= myRow["Customer_Maintenance"].ToString();
serviceAffect.Value=myRow["Systems/Services_Affected"].ToString();
email_Content.Value= myRow["Email_Content"].ToString();
email_Signature.Value= myRow["Email_Signature"].ToString();
email_From.Value=myRow["Email_From"].ToString();
email_To.Value=myRow["Email_To"].ToString();
email_Cc.Value=myRow["Email_Cc"].ToString();
email_Bcc.Value=myRow["Email_Bcc"].ToString();
}
}
else
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Non_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value = myRow["Customer_Maintenance"].ToString();
serviceAffect.Value = myRow["Systems/Services_Affected"].ToString();
email_Content.Value = myRow["Email_Content"].ToString();
email_Signature.Value = myRow["Email_Signature"].ToString();
email_From.Value = myRow["Email_From"].ToString();
email_To.Value = myRow["Email_To"].ToString();
email_Cc.Value = myRow["Email_Cc"].ToString();
email_Bcc.Value = myRow["Email_Bcc"].ToString();
}
}
The following is the button click for Save Button(for update command)
protected void save_click(object sender, EventArgs e)
{
//Button Click Save
/* String id = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",TextBox1.Text,id);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
*/
String cust = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
if (env.Value == "Production")
{
//String sql = String.Format("Update Customer_Production set Customer_Maintenance='{0}',Environment='{1}',[Systems/Services_Affected]='{2}',Email_Content='{3}',Email_Signature='{4}',Email_To='{5}',Email_Cc='{6}',Email_Bcc='{7}',Email_From='{8}' where Customer_Name like '{9}' ", "custMaintain.Value","env.Value","serviceAffect.Value","email_Content.Value","email_To.Value","email_Cc.Value","email_Bcc.Value","email_From.Value", "cust");
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'", email_Signature.Value,cust);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
}
else
{
}
}
I'm not sure why having a connection (or not) in the Page_Load would make a difference, but here's one thing that looks off to me:
String.Format(
"Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",
email_Signature.Value,
cust);
(I broke it into several lines because the part I'm interested in is the last part of the format string.)
You've set cust to "A" earlier in that method. So the SQL that will result will look (at the end) like this:
... where Customer_Name like 'A'
Unless you have a customer name that is exactly equal to A, that's not going to return anything, and therefore no records will be updated. You're forgetting the '%' wildcard.
I agree with all those who have pointed out that your code is vulnerable to SQL injection (and you'll also have a problem with single quotes), but just to show you what it needs to look like, here it is with the wildcard:
Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}%'

How to count total number of rows of an access database table?

string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr = "select * from quant_level1";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
DataSet data = new DataSet();
int i = data.Tables["quant_level1"].Rows.Count;
Label2.Text = i.ToString();
use
string cmdstr = "SELECT COUNT(*) FROM quant_level1";
With com.ExecuteScalar()
using(OleDbConnection conn = new OleDbConnection(constr))
using(OleDbCommand command = new OleDbCommand(cmdstr, conn))
{
conn.Open();
int count = (int)command.ExecuteScalar();
}
ExecuteScalar returns the first column of the first row in the result set returned by the query, here it give you row count.
you can use OleDbDataReader as you try in your code sample. but need to change the logic bit.
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("select * from quant_level1", con))
{
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
DataTable dt = new DataTable();
dt.Load(myReader);
int count = dt.Rows.Count;
}
}
Why you fail!
You have created data set but you haven't load data to dataset using your DataReader. So you will get zero row count at the end.
Looks like that you want to fill your DataSet and count the rows later:
DataSet data = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(com);
da.Fill(data);
int i = data.Tables[0].Rows.Count;
Label2.Text = i.ToString();
If you just want to count the rows, you can change the query to SELECT COUNT(*) FROM quant_level1 and get the return value like this:
int i = (int) com.ExecuteScalar();
Label2.Text = i.ToString();
You should do something like this:
Select count(*) from quant_level1
Change the command syntax executescalar to retrieve a single value
CommandText = "SELECT COUNT(*) FROM region";
Int32 count = (int32) ExecuteScalar();
Hope this can enlighten you a bit

How to populate data from SQL Server database columns to textboxes

I want to populate data from a SQL Server database from many columns to many textboxes .. I have a code to populate just one box .. can someone edit my code... I want to pull data and show it in Name, Address, Telephone No and Date ... plz help .. this code works for only one textbox..
Thanks in advance
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select * From PersonalUsers ", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
Name.Text = DR1.GetValue(0).ToString();
}
while (DR1.Read())
{
if(DR1.GetName() == "YourSQLColumnName")
{
YourTextBox.Text = (string) DR1["YourSQLColumnName"];
}
// Your Other textboxes and columns which you want to match should follow as this template
}
SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, _conn);
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable tbl = new System.Data.DataTable("Results");
tbl.Load(rdr);
if (tbl.Rows.Count > 0)
Name.Text = tbl.Rows[0]["column_name"].ToString();
string cs=System.Configuration.ConfigurationManager.ConnectionString["DBCS"].ConnectionString;
using(OracleConnection con=new OracleConnection(cs))
{
sql="select empname from Emp where empno='"+empno+"'";
OracleCommand cmd = new System.Data.OracleClient.OracleCommand(sql,con);
con.Open();
OracleDataReader rdr = cmd.ExecuteReader();
if(rdr.Read())
{
EmpName.Text=Convert.ToString(rd["empname"]);
}
}
I assume that you would like to take care of both more rows and more columns.
Try to specify the columns. It works without, but the performance is better if you do so.
I assume you have a class called PersonalUser with the specifed properties.
It is also nice to have it in an sorted order, so I added that
public List<PersonalUser> FetchMyData()
{
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select Name, Address, TelephoneNo,Date From PersonalUsers order by Name", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
var result = new List<PersonalUser>();
while (DR1.Read())
{
result.Add(new PersonalUser {
Name = DR1.GetString(0);
Address= DR1.GetString(1);
TelephoneNo = DR1.GetString(2);
Date = DR1.GetString(3)
}
);
}
return result;
}
I would also, if the need is getting much complex than this, conidering using Entity Framwork..

Categories