In listview im showing product information .On each row there is one select button on each row in itemTemplate .
if user click this button i want which bookid is clicked in selectedindexchanging event.
i bound listview like following
string str = "SELECT BookName,BookPrice, Description, bookid FROM productinfo Where Categoryid ='" + Request.QueryString["CategoryId"] + "'";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(str, conn);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
lstvwShopItems.DataSource = dt;
lstvwShopItems.DataBind();
Please give solution?
in order to get a certain column when selecting a row you need to fill the property datakeynames with the property of your choice.
msdn
getting the value of the property:
void lstvwShopItems_SelectedIndexChanged(Object sender, EventArgs e)
{
string value = lstvwShopItems.SelectedValue;
}
don't forget to set the OnSelectedIndexChanged on your listview to this method in the codebehind..
Related
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.
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
connection db_obj1 = new connection();
SqlConnection sql_obj = db_obj1.Connect();
if (this.DropDownList1.SelectedIndex >= 0)
{
string brand = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
string query = "Select Product,Model, NetPrice, Cost, Profit from products where Brand='" + brand + "'";
// SqlDataReader query_read = query.ExecuteReader();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(query, sql_obj);
// cmd.Parameters.AddWithValue("#tab",);
DataTable table = new DataTable();
adapter.SelectCommand = command;
adapter.Fill(table);
// Response.Write(dt.Rows.Count.ToString());
GridView grd = new GridView();
grd.FindControl("GridView1");
grd.DataSource = table;
grd.DataBind();
}
}
The problem is that when I run the code, I only see the drop down list and no GridView even when I select dofferent options. I tried debugging and it seems that the table DOES get filled and the only problem that I think is in the line 'grd.FindControl("GridView1").Is this the proper way to give a gridview a data source?
According to me you should not use like
string brand = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
on behalf that try as below
string brand = DropDownList1.SelectedItem.Text;
after that fire a query.
i hope it will halpful.
After Edit now use this code
string query = "Select Product,Model, NetPrice, Cost, Profit from products where Brand='" + brand + "'";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(query, sql_obj);
// cmd.Parameters.AddWithValue("#tab",);
DataSet ds = new DataSet();
DataTable table;
adapter.SelectCommand = command;
adapter.Fill(ds, "ABC");
table = ds.Tables["ABC"];
// Response.Write(dt.Rows.Count.ToString());
GridView grd = new GridView();
grd.FindControl("GridView1");
grd.DataSource = table;
grd.DataBind();
Explanation
adapter.Fill(ds, "ABC");
here ABC is a temp name of table you can take anything.
table = ds.Tables["ABC"];
and write here same table name as you have taken a temp table name.
now try it.
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());
}
}
I am trying to fill the gridview with the search results. Here is the UI of my "AddDropClasses" page:
When this page is loaded, i want the gridview to be filled the current courses of the current user, and i do this using the Register table. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string query = "select * from RegisterTable where StudentID='" + MyGlobals.currentID + "'";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
showCourses.DataSource = tab;
}
I load (come to) this page by clicking a button from another page. The problem is, the table shows no results. When i debugged i realized that Myglobals.ID has the value what i already expect. What can be the problem here? Can anyone help?;
Thanks
You forgot to databind showCourses. Add showCourses.DataBind(); after showCourses.DataSource = tab;
I have a text box with event name and two calendar controls to get the date and a button to display a gridview.
I need to display the grid with the details like eventname start date and end date from the database..
My code is .aspx.cs
protected void lnbtnSearch_OnClick(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=CTSINDLFVMOSS;Initial Catalog=DB_CGTPO_DEVE;Persist Security Info=True;User ID=*****;Password=*****");
SqlDataAdapter adapter = new SqlDataAdapter("select EventId,EventName,StartDate,EndDate,Tactics,Perct_VolLift,Perct_ROI from TableNamewhere (( EventName='" + textfield3 + "') and (StartDate= StartDate) and ( EndDate= EndDate))", conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
grdEventDetails.DataSource = ds;
grdEventDetails.
}
set grdEventDetails.AutoGenerateColumns = true;
add grdEventDetails.DataBind();
but it will look ugly (especially date fields) if you don't define the columns manually.