binding dropdownlist values to textbox - asp.net

When the user selects an order ID, the rest of the order information is displayed in label(s). Display the following: employee ID, order date, freight, shipped name, and country. This functionality should be implemented using direct data access programmatically.
Edit: code example and additional explanation.
String CS = onfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionStr‌​ing;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT OrderID FROM Orders", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "OrderID";
DropDownList1.DataValueField = "OrderID";
DropDownList1.DataBind();
Label1.Text = Convert.ToString(DropDownList1.SelectedItem.Text);
}
What I want is the other fields which are there in orders table to be displayed when a value is selected in the dropdownlist.

Can you make datatable from the SQL Query result, and then add items to dropdownlist from ID column. When you then select an item from DDL, you show the info where the row from datatable match the selected orderID.
I can write code if you want it isn't cleared what I'm meaning.
UPDATE: with code
var ds = new DataSet();
using (var conn = new SqlConnection(connection))
{
conn.Open();
var command = new SqlCommand("Your SQL Query", conn);
var adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
conn.Close();
} //Now you have a dataset, with one table that matches your query result.
//And now we can use a foreach loop to add every OrderID to dropdownlis
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
DDLname.Items.Add(dr[0].ToString());
}
}
//onSelectedValue event
string orderID = DDLname.Text.toString();
Label1.Text = orderID;
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
if(dr[0].toString().equals(orderID))
{
Label2.text = dr[1].toString();
Label3.text = dr[2].toString();
etc....
}
}
}

As you labelled your question with ASP.Net, I assume that this is part of an ASP.Net Webforms application. This means that the drop down list will be inside a web page in a browser. Not clear to me is whether you want the label to be displayed immediately when the user select the item, or only after a post to the server.
In the first case, you'll need javascript and probably something like Ajax or JSON to get the data you want to display for the selected item. In the second case, you could add an event handler for the SelectedIndex_Changed Event of your drop down list. This handler should do something like this:
string CS = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT OrderID FROM Orders WHERE OrderId = #OrderId", con);
cmd.Parameters.AddWithValue("#OrderId", DropDownList1.SelectedItem.Value);
con.Open();
if (reader.Read())
{
SqlDataReader reader = cmd.ExecuteReader();
Label1.Text = String.Format("Employee ID: {0}, order date: {1}, freight: {2}, shipped name: {3}, and country {4}."
, reader["employeeid"].ToString()
, reader["orderdate"].ToString()
, reader["freight"].ToString()
, reader["shipname"].ToString()
, reader["shipcountry"].ToString());
}
}

Related

How to insert dropdownlist value, text box value and gridviews selected row together?

How to insert dropdownlist value, text box value and gridviews selected row together?
Also attached the screenshot of the data insert:
enter image description here
enter image description here
enter image description here
I tend to prefer a add button that adds a row to the grid, and THEN you let the user edit the one row.
However, assuming you have those text boxes at the top of the screen, enter data, and then click a button to add to the database, and then re-fresh the GV?
I also don't see some button in the top area to add the data?
so, say a button added to the top area?
then this would add the row to the database:
protected void Button3_Click(object sender, EventArgs e)
{
string strSQL =
"INSERT INTO MyTable (Session, Class, Section, Term, Subject, HighestMark) " +
"VALUES (#Session, #Class, #Seciton, #Term, #Subject, #HighestMark)";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL,conn))
{
conn.Open();
cmdSQL.Parameters.Add("#Session", SqlDbType.Int).Value = DropSession.selecteditem.value;
cmdSQL.Parameters.Add("#Class", SqlDbType.Int).Value = DropClass.selecteditem.value;
cmdSQL.Parameters.Add("#Section", SqlDbType.Int).Value = DropSection.selecteditem.value;
cmdSQL.Parameters.Add("#Term", SqlDbType.Int).Value = DropTerm.selecteditem.value;
cmdSQL.Parameters.Add("#Subject", SqlDbType.Int).Value = DropSubject.selecteditem.value;
cmdSQL.Parameters.Add("#HighestMark", SqlDbType.Int).Value = HighestMark.Text;
cmdSQL.ExecuteNonQuery();
}
}
ReloadGrid(); // call routine to refresh the grid.
}
Edit: Adding the rows to a new table
Ok, so we are to take the top values, and then process each row of the grid, and take the ones with a check box and "insert" this data into a new table.
Ok, so the code will look like this:
protected void Button1_Click(object sender, EventArgs e)
{
string strSQL = "SELECT * FROM tblHotelsA WHERE ID = 0";
DataTable rstData = MyRst(strSQL);
foreach (GridViewRow gRow in GHotels.Rows)
{
CheckBox ckChecked = gRow.FindControl("ckSelected") as CheckBox;
if (ckChecked.Checked)
{
// this row was checked - add a new row
DataRow MyNewRow = rstData.NewRow();
MyNewRow["HotelName"] = txtHOtelName.Text; // exmaple control
MyNewRow["City"] = txtCity.Text; // example control above grid
// values from grid row
// tempalted columns, we use find control
MyNewRow["FirstName"] = (gRow.FindControl("txtFirstName") as TextBox).Text;
MyNewRow["LastName"] = (gRow.FindControl("txtLastName") as TextBox).Text;
// if data bound column, then we use cells collection
MyNewRow["FavorateFood"] = gRow.Cells[5];
// etc. etc.
rstData.Rows.Add(MyNewRow);
}
}
// done adding to table, write/save back to database.
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
cmdSQL.Connection.Open();
da.Update(rstData);
}
}
}
I also had this helper routine - I often use it all over the palce:
public DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
So, the concept here?
I pulled a blank row (SELECT * from table where ID = 0).
This gets me the database structure - and thus avoids a BOATLOAD of parameters in the sql.
this approach ALSO allows me to add a row to the table, and add "many" rows. And then execute ONE update to the database to write out (save) all the rows in one shot. So, this again reduced quite a bit of messy code.

How to select values in ASP.NET using SQL

I have a table in my database and two textbox and a button in my ASP.NET. I want to call database and select product name and code and if the entrance is correct I want to ok message, otherwise false!
Here is my code, but I did not get correct result.
try
{
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["WebDataBaseConnectionString"].ConnectionString;
SqlConnection scon = new SqlConnection(constring);
scon.Open();
SqlCommand cmd = new SqlCommand("select * from Product where Name=#Name and Code=#Code", scon);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Code", txtCode.Text);
SqlDataReader dr = cmd.ExecuteReader();
scon.Close();
Label1.Text = "The Product is in our list.Thank you";
}
catch(Exception)
{
Label1.Text = "The Product is not in our list.Sorry!";
}
Your query is modified as below
try
{
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["WebDataBaseConnectionString"].ConnectionString;
SqlConnection scon = new SqlConnection(constring);
scon.Open();
SqlCommand cmd = new SqlCommand("select * from Product where Name=#Name and Code=#Code", scon);
cmd.Parameters.Add("#Name", SqlDbType.Varchar).Value = txtName.Text;--Update the datatype as per your table
cmd.Parameters.Add("#Code", SqlDbType.Varchar).Value = txtCode.Text;--Update the datatype as per your table
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
--If you want to check the whether your query has returned something or not then below statement should be ommitted. Else you can check for a specific value while reader is reading from the dataset.
while (dr.Read())
{
--The returned data may be an enumerable list or if you are checking for the rows the read statement may be ommitted.
--To get the data from the reader you can specify the column name.
--for example
--Label1.Text=dr["somecolumnname"].ToString();
Label1.Text = "The Product is in our list.Thank you";
}
}
else
{
Label1.Text = "The Product is not in our list.Sorry!";
}
scon.Close();
}
catch (Exception)
{
Label1.Text = "The Product is not in our list.Sorry!";
}
Hope this answer will help you in resolving your query.

How do I insert grid view value into SQL Server database in ASP.NET?

I am creating a time in time out program in which when you click at a row in grid view it gets the data of the employee's last name, first name and middle name, then when I click the button, that data will be inserted to an inner joined table which is the time in time out table where the employee is set as Lname + Fname + Mname AS Employee_name
Here is my code - I need help with inserting the grid view data
SqlConnection con = new
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
string command = "INSERT INTO DTR(EmpRegID, CheckIn) VALUES (#EmpRegID, #CheckIn)";
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#CheckIn", DateTime.Now.ToString());
try
{
con.Open();
cmd.ExecuteNonQuery();
GridView2.DataBind();
}
finally
{
con.Close();
}
finally i have done it thank you guys for your answers so here is the code
string test1 = test.SelectedRow.Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
string command = "INSERT INTO DTR(RegEmpID, CheckIn) VALUES (#RegEmpID, #CheckIn)";
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#RegEmpID", test1);
cmd.Parameters.AddWithValue("#CheckIn", DateTime.Now.ToString());
try
{
con.Open();
cmd.ExecuteNonQuery();
GridView2.DataBind();
}
finally
{
con.Close();
}

How to pass a Session to a DataTable?

In my asp project I need to write all Items form the list box into database table using TVP. I have listbox, stored procedure (passing TVP - Table Valued Parameters). The main problem is that passing DataTable is NULL, but the Session isn't. I'll send you my code form aspx.cs file (only one block, if you'll nedd more, let me know).
protected void ASPxButton1_Click(object sender, EventArgs e)
{
//DataTable dts = Session["SelectedOptions"] as DataTable;
DataTable _dt;
//_dt = new DataTable("Items");
_dt = Session["SelectedOptions"] as DataTable;
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
}
SqlConnection con;
string conStr = ConfigurationManager.ConnectionStrings["TestConnectionString2"].ConnectionString;
con = new SqlConnection(conStr);
con.Open();
using (con)
{
SqlCommand sqlCmd = new SqlCommand("TestTVP", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = sqlCmd.Parameters.AddWithValue("#testtvp", _dt);
tvpParam.SqlDbType = SqlDbType.Structured;
sqlCmd.ExecuteNonQuery();
}
con.Close();
}
EDIT
Debugging Screenshot
You are not adding the new rows to the DataTable. You need something like this:
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
_dt.Rows.Add(dr);
}
A secondary concern is where are you initialising Session["SelectedOptions"]? It appears that every time ASPxButton1 is clicked the code will try and add Id and Name columns to it, even if it already contains those two columns. It would seem more logical to do something like:
_dt = Session["SelectedOptions"] as DataTable;
if (_dt == null)
{
_dt = new DataTable("Items");
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
Session.Add("SelectedOptions", _dt);
}

Display specific data on asp.net webpage from a microsoft sql express data table

I have been looking around the internet for a way to display specific content from a sql data table. I was hoping that I could display the Content column according to the Id column value.
alt text http://photos-h.ak.fbcdn.net/hphotos-ak-snc3/hs031.snc3/11852_1241994617732_1465331687_655971_2468696_n.jpg
If you want to have exactly one value from one single record, you can use the ExecuteScalar method of the SqlCommand class:
string title = null;
using (SqlConnection conn = new SqlConnection("your-connection-string"))
using (SqlCommand cmd = new SqlCommand(
"select ContentTitle from {put table name here} where id = 4", conn))
{
conn.Open();
title = (string)conn.ExecuteScalar();
}
if (!string.IsNullOrEmpty(title))
{
// assign title to suitable asp.net control property
}
If you want to be able to do this for various ids, do not just concatenate a new sql string. I will repeat that: do not just concatenate a new sql string. Use parameters instead:
string title = null;
using (SqlConnection conn = new SqlConnection("your-connection-string"))
using (SqlCommand cmd = new SqlCommand(
"select ContentTitle from {put table name here} where id = #id", conn))
{
SqlParameter param = new SqlParameter();
param.ParameterName = "#id";
param.Value = yourIdGoesHere;
cmd.Parameters.Add(param);
conn.Open();
title = (string)conn.ExecuteScalar();
}
if (!string.IsNullOrEmpty(title))
{
// assign title to suitable asp.net control property
}
Update
Sample aspx page. First some markup (let's say the file is called example.aspx):
<body>
<form id="Form1" runat="server">
Title: <asp:Label id="_titleLabel"
Text="{no title assigned yet}"
runat="server"/>
</form>
</body>
...and in the code-behind (that would be called example.aspx.cs; I have included only the Page_Load event for simplicity):
protected void Page_Load(object sender, EventArgs e)
{
int id;
try
{
if (int.TryParse(Request.QueryString["id"], out id))
{
_titleLabel.Text = GetContentTitle(id);
}
else
{
_titleLabel.Text = "no id given; cannot look up title";
}
}
catch (Exception ex)
{
// do something with the exception info
}
}
private static string GetContentTitle(int id)
{
using (SqlConnection conn = new SqlConnection("your-connection-string"))
using (SqlCommand cmd = new SqlCommand(
"select ContentTitle from {put table name here} where id = #id", conn))
{
SqlParameter param = new SqlParameter();
param.ParameterName = "#id";
param.Value = yourIdGoesHere;
cmd.Parameters.Add(param);
conn.Open();
return (string)conn.ExecuteScalar();
}
}
Disclaimer: the code is written directly into the answer window and not tested (I don't have access to a development environment right now) so there may be errors

Resources