I did not know what exactly to write in the title. If you think its an incorrect title I'll change it.
Heres the problem. I am binding a dropdownlist to a dataset (a table) from where I need fields like Name, AddressLine1, AddressLine2, City, Email, Country, etc... And I want to display these fields (values) on labels. Heres the complete code:
public String GetSessionObject()
{
string strSession = "";
if (HttpContext.Current.Session["SessionEmail"] != null)
{
strSession = HttpContext.Current.Session["SessionEmail"].ToString();
}
return strSession;
}
public DataSet BindDropDownListToAUserAddress()
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();
string strQuery = "SELECT *, FirstName +' '+ LastName as FullName from AUserAddress where AUser_ID = (Select ID from AUser where Email='" + GetSessionObject() + "')";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(ds, "AUserAddress");
con.Close();
return ds;
}
ddlName.DataSource = objBindDDL.BindDropDownListToAUserAddress().Tables["AUserAddress"];
ddlName.DataTextField = "FullName";
ddlName.DataBind();
lblDisplayAddressLine1.Text = objBindDDL.BindDropDownListToAUserAddress().Tables["AUserAddress"].Columns.("AddressLine1").ToString();-----------????
This is where I am stuck. I need values from specific columns to go on specific labels. What option(s) do I have? Please guide....
What I have understand your problem, for that you can do this
// Get User's Details
DataSet ds=BindDropDownListToAUserAddress();
// Now from this dataset you can get the specific column like this
if(ds!=null && ds.Tables.Count>0)
{
// I am assuming that your table contains single row of specific user
string AddressLine1= ds.Tables[0].Rows[0]["AddressLine1"].ToString();
string AddressLine2= ds.Tables[0].Rows[0]["AddressLine2"].ToString();
}
Related
UPDATE - PROBLEM SOLVED
Just in case to retrieve all data at once, using a single SQL statement to retrieve joined table results, but couldn't access it and received error below
Exception details: System.IndexOutOfRangeException: crsName
By the way, anyone please suggest a more convenient way to deal with a GridView that need to display a JOIN result.
Instead of this approach - https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.datacontrolfieldcollection.add?view=netframework-4.8
BoundField courseBF = new BoundField();
courseBF.DataField="courseName";
courseBF.HeaderText="Course Name";
//Which is stated in Microsoft Document
Here's the code receive error
string userID = (string)Session["userID"];
string sql = "SELECT courseID from gpaSem where stuID=#userID";
string temp = "";
string temp02 = "";
string[] crsID;
string[] crsName;
string[] grade;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#userID", userID);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
temp += ("!" + dr["courseID"]);
}
crsID = temp.Split('!');
crsID = crsID.Skip(1).ToArray();//course ID get
dr.Close();
con.Close();
con.Open();
temp = "";
foreach (string crs in crsID)
{
sql = "SELECT G.grade AS grade, C.crsName AS crsName FROM gpaSem G, course C WHERE G.courseID=C.courseID AND G.courseID=#courseID";
cmd.Parameters.AddWithValue("#courseID", crs);
dr = cmd.ExecuteReader();
if(dr.Read())
{
temp += "!" + dr["crsName"];//error
temp02 += "!" + dr["grade"];
}
}
crsName = temp.Split('!');
crsName = crsName.Skip(1).ToArray();//course name get
grade = temp02.Split('!');
grade = grade.Skip(1).ToArray();//grade get
dr.Close();
con.Close();
My point is, is that I should explicitly use JOIN in SQL statement or the way I access the value is wrong?
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();
}
I'am new in asp.net. I want to select values from database table.
If it was PHP I would do it like following code.
$query = mysql_query(" SELECT * FROM Table WHERE id = ".$d." ");
while($row = mysql_fetch_array($query))
{
$firstname = $row['firstname'];
$lastname = $row['lastname'];
}
How would I do if it was in asp.net if I use SqlConnection ...and SqlCommand or maybe if there is some beter Connections.... Thank you in advance guys....
//Create a command, using a parameter
var command = new SqlCommand("select firstname, lastname from table where id=#id");
command.Parameters.AddWithValue("id", id);
DataTable dt = new DataTable();
//use a using statement to ensure the connection gets disposed properly
using(var connection = new SqlConnection("connectionstring"))
{
command.Connection = connection;
connection.Open();
//execute the command and load the results in a data table
dt.Load(command.ExecuteReader());
}
//loop through the results of the data table
foreach(var row in dt.Rows)
{
var firstname = row.Field<string>("firstname");
var lastname = row.Field<string>("lastname");
//do something with firstname and lastname
}
This isn't a direct translation since I'm storing the values in a DataTable, but that is usually better than leaving the data connection open.
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"].ConnectionString;
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());
}
}
The below code is the web method (is the most common one as you can see it everywhere), but i keep getting the error from the title. I am at the beginning with .NET, so if anyone can point me into the right direction , please do so.
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["mySQLconn"].ConnectionString);
[WebMethod(Description = "Select Customers")]
public string GetVersionofSelectedCustomer(string versionEmail)
{
string select = "SELECT version FROM customer WHERE EMAIL = '" + versionEmail + "'";
SqlDataAdapter adapter = new SqlDataAdapter(select, myConnection);
DataSet custDS = new DataSet();
//adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(custDS, "Customers");
return custDS;
}
connection is defined in the Web.config (local connection) and return custDS; is where it fails.
You are returning dataset so you should use return type as Dataset
public Dataset GetVersionofSelectedCustomer(string versionEmail)
{
//add your code to return dataset
}
The return type of your function is string and you are trying to return a DataSet object. You can try like this:
public DataSet GetVersionofSelectedCustomer(string versionEmail)
{
string select = "SELECT version FROM customer WHERE EMAIL = '" + versionEmail + "'";
SqlDataAdapter adapter = new SqlDataAdapter(select, myConnection);
DataSet custDS = new DataSet();
//adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(custDS, "Customers");
return custDS;
}
Your method signature returns a string, but you are returning a DataSet - it's not clear exactly what you want to do here - possibly just change the signature to return a dataset?