SQLConnection bringing data to TextBox - c#

I know this looks really simple but i've been looking for an answer for hours with no luck.
I want to fill my row values into a bunch of textboxes. How can I specify that [CompanyName] is going to be used by the companyName textbox? Please keep it as simple as possible (beginner level).
string customerUniqueID = "test";
string constr = ConfigurationManager.ConnectionStrings["SQLConnection"].ToString(); // connection string
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("SELECT * FROM [Customers] WHERE [UniqueID] = #UniqueID", con); // table name
com.Parameters.Add("#UniqueID", SqlDbType.Int);
com.Parameters["#UniqueID"].Value = customerUniqueID;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
companyName.Text = ?????????

string customerUniqueID = "test";
string constr = ConfigurationManager.ConnectionStrings["SQLConnection"].ToString(); // connection string
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("SELECT * FROM [Customers] WHERE [UniqueID] = #UniqueID", con); // table name
com.Parameters.Add("#UniqueID", SqlDbType.Int);
com.Parameters["#UniqueID"].Value = customerUniqueID;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds, "Customers");
companyName.Text = ds.Tables[0].Rows[0]["CompanyName"].ToString();

I will recommend some changes in your code:
Your sql query returning result from one set, so you can use DataTabe instead of DataSet.
To fill results from DB to your DataTable you can use SqlAdapter.Fill() method.
Use Field() generic method (more examples of Field()) to get values from your DataTable.
Use using blocks for disposable objects, or at least make sure you've closed them after.
There is no need of con.Open() to open connection when using Fill() method, because from MSDN:
The Fill method implicitly opens the Connection that the DataAdapter is using if it finds that the connection is not already open. If Fill opened the connection, it will also close the connection when Fill is finished. This can simplify your code when dealing with a single operation such as a Fill or an Update.
string customerUniqueID = "test";
string constr = ConfigurationManager.ConnectionStrings["SQLConnection"].ToString(); // connection string
using(SqlConnection con = new SqlConnection(constr))
{
SqlCommand com = con.CreateCommand();
com.CommandText = "SELECT * FROM [Customers] WHERE [UniqueID] = #UniqueID";
com.Parameters.Add("#UniqueID", SqlDbType.Int);
com.Parameters["#UniqueID"].Value = customerUniqueID;
using(SqlDataAdapter da = new SqlDataAdapter(com))
{
DataTable dt = new DataTable();
da.Fill(dt);
companyName.Text = dt.Rows[0].Field<string>("CompanyName");
}
}
Please feel free to comment, if I missed something.

Related

How to convert selected date to string and view on DataGrid

I'm trying to search for data between two dates and show on the datagrid. However I'm getting an error says that toString is unable to convert the selected date to string.
private void searchButton_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=xxxxxx;Password=xxxxxx");
SqlDataAdapter sda = new SqlDataAdapter("SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where JoiningDate between'"+fromText.SelectedDate.Value.ToString("MM/DD/YYYY")+"'AND'"+toText1.SelectedDate.Value.ToString("MM/DD/YYYY")+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
UPDATE:
I have changed my code and have gotten rid of the error. However, no data is showing on in the grid, only an empty row. Would anyone know why that is?
string sqlStr = "SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where RentDate between #fromDT AND #toDT";
string connStr = #"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=xxxxxx;Password=xxxxxx";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr, con))
{
sda.SelectCommand.Parameters.Add(new SqlParameter("#toDT", SqlDbType.DateTime)).Value = toText1.SelectedDate.Value;
sda.SelectCommand.Parameters.Add(new SqlParameter("#fromDT", SqlDbType.DateTime)).Value = fromText.SelectedDate.Value;
DataSet ds = new DataSet();
con.Open();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
There are some issues in your code.
Your con connection string didn't' open when you use Fill method, so you can't execute the SQL statement.
Your code has a SQL-Injection problem, I would suggest you use parameters instead of connected SQL statement string, make sure your parameter data type size as same as your table schema.
You didn't return the resource when you finish you have executed your SQL statement, I would use using statement because the purpose of Using statement is that when control will reach the end of using it will dispose that object of using block and free up memory. its purpose is not only for auto connection close, basically it will dispose of the connection object and obviously, the connection also closed due to it.
using SqlParameter class to make it.
private void searchButton_Click(object sender, RoutedEventArgs e)
{
string sqlStr = "SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where JoiningDate between #fromDt AND #toDt";
string connStr = #"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=DDQ4_Melveena;Password=xxxxx";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr, con))
{
sda.SelectCommand.Parameters.Add(new SqlParameter("#toDt", SqlDbType.DateTime)).Value = toText1.SelectedDate.Value;
sda.SelectCommand.Parameters.Add(new SqlParameter("#fromDt", SqlDbType.DateTime)).Value = fromText.SelectedDate.Value;
DataSet ds = new DataSet();
con.Open();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
}

Fill combobox from SQL database with specific parameter

I have problem to get specific value from sql server with parameter can anybody explain me why it works on winfom but not on wpf and how i can fix it
my code:
private void UpdateItems()
{
COMBOBOX1.Items.Clear();
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = ds.Tables[0].Columns["FR"].ToString();
COMBOBOX1.SelectedValuePath = ds.Tables[0].Columns["FC"].ToString();
}
The program when execute this function crash with error:
System.Data.SqlClient.SqlException: 'Invalid column name
'some_specific_string'.'
the solution is
SqlConnection sqlConnection = new SqlConnection(Properties.Settings.Default.constring.ToString());
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM CLIENTS where cod_cli=#cod", sqlConnection);
sqlCmd.Parameters.AddWithValue("#cod", cod_cli.Text);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
COMBOBOX1.Items.Add(sqlReader["FR"].ToString());
}
sqlReader.Close();
}
The query doesn't recognize string as parameter but adding as SQL parameter it works.
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
//Populate the combobox
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = "FR";
COMBOBOX1.SelectedValuePath = "FC";
where "FR" and "FC" are existing columns in your SELECT Query.

how can i put # in select sql statement?

I have to use the "#"(I don't know it's name). I can use it in update delete or insert statements but I cannot use it in there it gives URL MUST BE DECLARED
//SQL string to count the amount of rows within the OSDE_Users table
string sql = "SELECT * FROM RSSFeeds where URL = #URL";
SqlCommand cmd = new SqlCommand(sql, Connect());
cmd.Parameters.Add("#URL", SqlDbType.VarChar, 500).Value = url;
closeConnection();
SqlDataAdapter adapt = new SqlDataAdapter(sql, Connect());
DataSet ds = new DataSet();
adapt.Fill(ds);
// result of query filled into datasource
adapt.Dispose();
closeConnection();
return ds;
I can only suppose that this line is not correct:
cmd.Parameters.Add("#URL", SqlDbType.Int).Value = url;
Probably URL is not an Int but a NVarChar or other character type
If this is the case then change your line in this way
(255 is the supposed length of your field URL)
cmd.Parameters.Add("#URL", SqlDbType.NVarChar, 255).Value = url;
And, by the way, '#' is called "Parameter Prefix"
EDIT: Seeing the last edit from the OP I update my answer to show what I think is the correct way to go.
//SQL string to count the amount of rows within the OSDE_Users table
string sql = "SELECT * FROM RSSFeeds where URL = #URL";
DataSet ds = new DataSet();
using(SqlConnection cnn = Connect())
using(SqlCommand cmd = new SqlCommand(sql, cnn))
{
cmd.Parameters.Add("#URL", SqlDbType.VarChar, 500).Value = url;
using(SqlDataAdapter adapt = new SqlDataAdapter(cmd))
{
adapt.Fill(ds);
}
}
return ds;
What I have changed:
Encapsulated every disposable object inside an using statement that
is guaranteed to close/dispose objects
Called Connect() just one time and captured the SqlConnection returned to
reuse without creating another one
Created the SqlDataAdapter using the SqlCommand created before (so
the #URL parameter reaches the Sql)
The OP used a closeConnection() and we don't see the internal of this method, but I think that using is enough to close and dispose the connection.
EDIT: The line that creates SqlDataAdapter should be
using(SqlDataAdapter adapt = new SqlDataAdapter(cmd))
cmd.Parameters.AddWithValue("#URL", url);
should work

Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'PRC0000001'

i keep getting this error, i dont know why, im still new to c#. kindly help me figure this out please. i have two dropdownlist that would populate data based on first dropdownlist selected value.
when i select a value on the first dropdownlist, i get that error..
here is my code..
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//read sql server connection string from web.config file
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT CITY_NAME FROM emed_city WHERE PROVINCE_CODE ="+ddlProvince.SelectedValue, conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlProvince.DataBind();
}
}
It happens because you passed the raw value without quotes, so the database thought you mean field name.
Avoid this all mess by using Parameters:
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT CITY_NAME FROM emed_city WHERE PROVINCE_CODE=#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
This answer is an alternative approach, when using Parameters isn't viable.
The SQL interpreter is confusing values with database objects.
You can save the interpreter from confusion by making your SQL statement more explicit. Surround columns and table names with [ square brackets and wrap any values in single quotes.
using (conn)
{
var whereValue = "'"+ddlProvince.SelectedValue+"'";//wrap in single quotes
conn.Open();
SqlCommand comm = new SqlCommand("SELECT [CITY_NAME] FROM [emed_city] WHERE [PROVINCE_CODE] = "+whereValue;
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
The square brackets explicitly state to the SQL Intepreter that it is dealing with a database object. The single quotes inform the interpreter it is dealing with a value.
Now the interpreter won't mistake your value for a column name.

C# -> Retrieving dataset from SQL Server 2008

I have a table called NAMES in my SQL Server database. I am trying to retrieve the entire table and put it into a dataset:
//get the connection string from web.config
string connString = ConfigurationManager.ConnectionStrings["Platform"].ConnectionString;
DataSet dataset = new DataSet();
using (SqlConnection conn = new SqlConnection(connString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("NAMES", conn);
adapter.Fill(dataset);
}
This throws a sql exception though,
"Invalid Object Name NAMES"...
What am I doing wrong?
Open the connection !!!!!!
//get the connection string from web.config
string connString = ConfigurationManager .ConnectionStrings["Platform"].ConnectionString;
DataSet dataset = new DataSet();
using (SqlConnection conn = new SqlConnection(connString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("select * from [NAMES]", conn);
conn.Open();
adapter.Fill(dataset);
}
You're not passing an actual SQL select command to the SqlCommand constructor.
First check whether Select * from dbo.[Names] is wroking in ur sql ?
string connString = ConfigurationManager .ConnectionStrings["Platform"].ConnectionString;
Dataset ds=new Dataset();
SqlConnection con = new Sqlconnection(connString);
SqlDataAdapter adapter = new SqlDataAdapter("Select * from dbo.[Names]",con);
adapter.Fill(ds);

Categories