Skip row in gridview asp.net - c#

I have a gridview showing academy name and a dropdown list. The dropdown list have value of 0-13, 0 is the "Please select option". I want when the save button it skip those row where there is no selection in the dropdown therefore 0.
Here is my code for the gridview:
<asp:GridView ID="gdvAcadSelec" runat="server" AutoGenerateColumns="False"
DataKeyNames="acad_Id"
DataSourceID="srcAcademy"
OnRowDataBound="gdvAcadSelec_RowDataBound"
CssClass="table table-striped table-bordered"
EnableViewState="False">
<Columns>
<asp:BoundField DataField="acad_Id" HeaderText="Id" />
<asp:BoundField DataField="acad_name" HeaderText="Academy" />
<asp:TemplateField HeaderText="Choice">
<ItemTemplate>
<asp:DropDownList ID="ddlPref" OnTextChanged="ddlPref_TextChanged" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnsubmit" CssClass="btn btn-info" OnClick="btnsubmit_Click" runat="server" Text="Submit" />
<asp:ObjectDataSource ID="srcAcademy"
TypeName="dataAccessLayer"
SelectMethod="getAcademy"
runat="server" />
The code behind for the binding of item for the column Choice:
protected void gdvAcadSelec_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("ddlPref") as DropDownList);
ddlCountries.Items.Insert(0, new ListItem("Please select"));
ddlCountries.Items.Insert(1, new ListItem("1"));
ddlCountries.Items.Insert(2, new ListItem("2"));
ddlCountries.Items.Insert(3, new ListItem("3"));
ddlCountries.Items.Insert(4, new ListItem("4"));
ddlCountries.Items.Insert(5, new ListItem("5"));
ddlCountries.Items.Insert(6, new ListItem("6"));
ddlCountries.Items.Insert(7, new ListItem("7"));
ddlCountries.Items.Insert(8, new ListItem("8"));
ddlCountries.Items.Insert(9, new ListItem("9"));
ddlCountries.Items.Insert(10, new ListItem("10"));
ddlCountries.Items.Insert(11, new ListItem("11"));
ddlCountries.Items.Insert(12, new ListItem("12"));
ddlCountries.Items.Insert(13, new ListItem("13"));
}
On click save button:
protected void btnsubmit_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gdvAcadSelec.Rows)
{
DropDownList ddlorder = (DropDownList)row.FindControl("ddlPref");
string acadID = row.Cells[0].Text;
string order = ddlorder.SelectedValue.ToString();
SqlCommand scmd = new SqlCommand();
scmd.CommandType = CommandType.Text;
scmd.CommandText = "Insert into tblAcademy_Selection (acad_Id,stud_Id,order_preference) values (#acad,#stud,#order)";
scmd.Connection = con;
scmd.Parameters.AddWithValue("#acad", acadID);
scmd.Parameters.AddWithValue("#stud", 60);
scmd.Parameters.AddWithValue("#order", order);
con.Open();
scmd.ExecuteNonQuery();
con.Close();
}
}
The problem with this code is when it is saving to the database ,those dropdowns list who have value "please select" is also being save and this crash my website.
What can I do to skip those dropdown that do not have value selected?
Thank you in advance.

(Edited per request from OP)
Simply use an if() statement to skip the values you don't want to insert.
string order = ddlorder.SelectedIndex.ToString();
if (order != "0") { // Some may argue that it should be !order.equals("0") but in C# it doesn't matter.
SqlCommand scmd = new SqlCommand();
scmd.CommandType = CommandType.Text;
.
.
}
And if you're a prudent (and paranoid) programmer, you won't trust anything sent from the browser, you'll check to make sure the variable order is the appropriate type and is within the range of values you expect as well.

Related

change dropdown list item selecting radio button in grid view

pictureIf I selected male radio button then different options show in dropdown list if I select Female then show different options in dropdown list with the help of RowDataBound Method.
Ok, in fact much of the trick and issue is that when you load the existing grid of data, we ALSO have to setup the radiobutton choice and the drop down list.
So, say we have this grid:
<asp:GridView ID="GHotels" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" cssclass="table" OnRowDataBound="GHotels_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Gender">
<ItemTemplate>
<asp:RadioButtonList ID="RGender" runat="server"
RepeatDirection="Horizontal"
Text='<%# Eval("Gender") %>' >
<asp:ListItem>M</asp:ListItem>
<asp:ListItem>F</asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Option">
<ItemTemplate>
<asp:DropDownList ID="cboOption" runat="server"
DataValueField="ID"
DataTextField="Feature" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Code to load the grid is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GHotels.DataSource = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName");
GHotels.DataBind();
}
}
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;
}
And we now have this:
but, note how we STILL have to load up the radiobutton list and ALSO setup the combo box that gives a different set of choices.
So, we add this code to the row data bound event.
protected void GHotels_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = e.Row.DataItem as DataRowView;
// based on Gender fill cbo box
string strSQL = "SELECT ID, Feature FROM tblHotelOptions ";
if (gData["Gender"].ToString() == "M")
{
strSQL += "WHERE Gender = 'M'";
}
else
{
strSQL += "WHERE Gender = 'F'";
}
strSQL += " ORDER BY Feature";
DropDownList cboOption = e.Row.FindControl("cboOption") as DropDownList;
cboOption.DataSource = MyRst(strSQL);
cboOption.DataBind();
cboOption.Items.Insert(0, new ListItem("Select", "0"));
if (gData["HotelOption"] != null)
cboOption.SelectedValue = gData["HotelOption"].ToString();
}
}
So, for each grid row, we process the data row information, and conditional load up the drop down list with choices based on gender.
Now, that works for "loading", but now we need to add the event and code for when we CHANGE the radio button choice.
so, in the markup, we add this event to the radiobutton:
We have to use markup and intel-sense to pop up the choice to create a new event, like this:
So, we added autopostback=true to the radio button list, and the selected change event.
So, now when you change the radio choice, we need to run code to change the drop down list choices.
So, that code can look like this:
protected void RGender_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList rBtn = sender as RadioButtonList;
GridViewRow gRow = rBtn.NamingContainer as GridViewRow;
string strSQL = "SELECT ID, Feature FROM tblHotelOptions ";
if (rBtn.SelectedItem.Text == "M")
// based on Gender fill cbo box
{
strSQL += "WHERE Gender = 'M'";
}
else
{
strSQL += "WHERE Gender = 'F'";
}
strSQL += " ORDER BY Feature";
DropDownList cboOption = gRow.FindControl("cboOption") as DropDownList;
cboOption.DataSource = MyRst(strSQL);
cboOption.DataBind();
cboOption.Items.Insert(0, new ListItem("Select", "0"));
}
In fact, the code is VERY much the same as how we had to load up the grid.

2 DropDownLists on each row of Gridview

I have a gridview that is being dynamically created based on the database. Some rows of the gridview have 2 DropDownLists, while others do not depending on the item in the row. The second DropDownList of the row is dynamically created based on the selection of the first DrowpDownMenu. Everything works as it should except, if you make the selections on the first row, then change the selection of the first DropDownList of the seccond row or click the update button, it will reset the second DropDownList of the first row. This is obviously due to PostBack. But I'd like to maintain the selection until all DropDownLists have been selected and I save the changes to the DB. Any help would be very appreciated.
My Gridview:
<asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False" ShowFooter="True"
GridLines="Vertical" CellPadding="4" CssClass="table table-striped table-bordered"
OnRowDataBound="CartList_RowDataBound">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ID" SortExpression="ProductID" />
<asp:BoundField DataField="Product.ProductName" HeaderText="Name" />
<asp:BoundField DataField="Product.UnitPrice" HeaderText="Price (each)" DataFormatString="{0:c}" />
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text='<%# Eval("Quantity") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Size">
<ItemTemplate>
<asp:DropDownList ID="Sizeddl" runat="server" Font-Size="Medium"
AutoPostBack="true" ForeColor="Black" OnSelectedIndexChanged="Sizeddl_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Color">
<ItemTemplate>
<asp:DropDownList ID="ColorNameddl" runat="server"
Font-Size="Medium" ForeColor="Black">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Total">
<ItemTemplate>
<%#: String.Format("{0:c}", ((Convert.ToDouble( Eval("Quantity") )) * Convert.ToDouble(Eval("Product.UnitPrice"))))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remove Item">
<ItemTemplate>
<asp:CheckBox ID="Remove" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div>
<p></p>
<strong>
<asp:Label ID="LabelSubtotal" runat="server" Text="SubTotal: "></asp:Label>
<asp:Label ID="lblSubtotal" runat="server" EnableViewState="false"></asp:Label>
</strong>
<p></p>
<strong>
<asp:Label ID="LabelTax" runat="server" Text="Tax Total: "></asp:Label>
<asp:Label ID="lblTax" runat="server" EnableViewState="false"></asp:Label>
</strong>
<p></p>
<strong>
<asp:Label ID="LabelTotalText" runat="server" Text="Order Total: "></asp:Label>
<asp:Label ID="lblTotal" runat="server" EnableViewState="false"></asp:Label>
</strong>
</div>
<br />
<table>
GridView Load:
DataTable rstSize = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
{
decimal cartTotal = 0;
cartTotal = usersShoppingCart.GetTotal();
if (cartTotal > 0)
{
// Display Total.
lblSubtotal.Text = String.Format("{0:c}", usersShoppingCart.GetSubtotal());
lblTax.Text = String.Format("{0:c}", usersShoppingCart.GetTax());
lblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
}
else
{
lblSubtotal.Text = "";
lblTax.Text = "";
lblTotal.Text = "";
ShoppingCartTitle.InnerText = "Shopping Cart is Empty";
UpdateBtn.Visible = false;
CheckoutImageBtn.Visible = false;
}
if (!IsPostBack)
{
LoadGrid();
}
}
}
void LoadGrid()
{
// Load Cart Items.
using (ShoppingCartActions actions = new ShoppingCartActions())
{
var _db = new ProductContext();
string cartId = actions.GetCartId();
var cart = _db.ShoppingCartItems.Where(
c => c.CartId == cartId).ToList();
// Create DataTable for Colors
rstSize.Columns.Add("SizeName", typeof(string));
var row = rstSize.NewRow();
row["SizeName"] = "S";
row["SizeName"] = "M";
row["SizeName"] = "L";
row["SizeName"] = "XL";
row["SizeName"] = "2XL";
CartList.DataSource = cart;
CartList.DataBind();
// Hide DropDown Lists for rows that they are not needed for.
for (int i = 0; i < CartList.Rows.Count; i++)
{
DropDownList sizeDDL = CartList.Rows[i].FindControl("Sizeddl") as DropDownList;
DropDownList colorDDL = CartList.Rows[i].FindControl("ColorNameddl") as DropDownList;
IOrderedDictionary rowValues = new OrderedDictionary();
rowValues = GetValues(CartList.Rows[i]);
var _prodID = Convert.ToInt32(rowValues["ProductID"]);
var _prod = (from c in _db.Products
where c.ProductID == _prodID
select c.CategoryID).FirstOrDefault();
if (_prod != 1)
{
sizeDDL.Visible = false;
colorDDL.Visible = false;
}
}
}
}
My RowDataBound:
protected void CartList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = (DataRowView)e.Row.DataItem;
// Populate and select Color from DB.
DropDownList sizeDDL = (DropDownList)e.Row.FindControl("Sizeddl");
sizeDDL.DataSource = rstSize;
sizeDDL.DataBind();
sizeDDL.Items.Insert(0, new ListItem("Select Size", "0"));
sizeDDL.SelectedValue = gData["SizeName"].ToString();
// Load Color DDL
var _size = sizeDDL.SelectedItem.Text;
int _prod = Convert.ToInt32(e.Row.Cells[0].Text);
var _db = new ProductContext();
var qryColor = (from p in _db.ProductAttributes
join c in _db.Colors
on p.ColorID equals c.ColorID
where p.SizeName == _size & p.ProductID == _prod
select new { p.ColorID, c.ColorName }).Distinct().ToList();
DropDownList colorDDL = (DropDownList)e.Row.FindControl("ColorNameddl");
// Create DataTable for Colors
DataTable rstColor = new DataTable();
rstColor.Columns.Add("ColorID", typeof(int));
rstColor.Columns.Add("ColorName", typeof(string));
foreach(var item in qryColor)
{
var row = rstColor.NewRow();
row["ColorID"] = item.ColorID;
row["ColorName"] = item.ColorName;
rstColor.Rows.Add(row);
}
// Bind Color Drop Down List to DataTable.
colorDDL.DataSource = rstColor;
colorDDL.DataBind();
colorDDL.Items.Insert(0, new ListItem("Select Color", "0"));
colorDDL.SelectedValue = gData["ColorName"].ToString();
}
}
My SelectedIndexChanged
protected void Sizeddl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList sizeDDL = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)sizeDDL.NamingContainer;
string strSize = sizeDDL.SelectedItem.Text;
DropDownList colorDDL = (DropDownList)gRow.FindControl("ColorNameddl");
if (strSize != "Choose one")
{
using (ProductContext context = new ProductContext())
{
int _prodID = Convert.ToInt32(gRow.Cells[0].Text);
var _size = sizeDDL.SelectedItem.Text;
var qryColor = (from p in context.ProductAttributes
join c in context.Colors
on p.ColorID equals c.ColorID
where p.SizeName == _size & p.ProductID == _prodID
select new { p.ColorID, c.ColorName }).Distinct().ToList();
if (qryColor.Count > 0)
{
colorDDL.DataSource = qryColor;
colorDDL.DataTextField = "ColorName";
colorDDL.DataValueField = "ColorID";
colorDDL.DataBind();
colorDDL.Items.Insert(0, new ListItem("Select Color", "0"));
colorDDL.Enabled = true;
}
else
{
colorDDL.Items.Clear();
colorDDL.Items.Insert(0, new ListItem("No Colors Available", "0"));
colorDDL.Enabled = false;
}
}
}
}
if you make the selections on the first row
By "selections" are we to assume make changes - or select/change a value in the combo boxes, right?
I'd like to maintain the selection until all DropDownLists have been selected and I save the changes to the DB. Any help would be very appreciated.
A grid view will and should handle post backs on the page. After all, even outside of the GV, any old button or control can and will cause post-backs.
There is no reason that changes to ANY grid row by users, and that includes drop down lists (DDL) should matter. And operations on one row should not effect operations on other rows. The so called "view" state of the GV is automatic, and for the most part you should not have to worry.
So, it not at all clear why you posted the "add row", since all of this question centers on editing or making changes to the current row. (for us, say next week or when ever, we can look at or deal with the row created, but for now lets concentrate on the changes to a given row, and why for some reason you see effects in other rows - you should not be seeing this.
Tops on the list?
While controls - including a GV can and should handle post-backs without issue?
That is NOT the case if a post-back causes a re-bind of the grid. If that is to occur, then you going have issues.
So, tops on the list?
You left out how/when/where you are loading up the GV.
(the MOST important part!!!!).
Next up?
You do NOT want nor need to show the row PK id in the GV. These numbers not only mean nothing to the end user but it also a security risk - PK row numbers don't need to be displayed, and in fact do not even need to be included in the row markup. We again can leave that issue for another day, but you can (and should consider) using DataKeys for the row PK id operations. We assume no duplicate PK row id in the database, right? In other words, make sure you have a database row PK "id" in your data.
So, you can in the future, remove that ProductID. GV has a special feature for dealing with the PK row id - and we should be using that. (Datakeys)
Ok, now that we cleared up the above?
In the page load event, we need to load the GV, but ONLY on first page load - after that, we can't re-load the GV (bind again), else you WILL lose your changes, and edits to the GV.
Also, you might want to consider a save button at the bottom - to save all gv changes - in place of doing this row by row. (but, one thing at a time here).
So first up, the code to load the GV, should be in page load.
Next up, that code has to ONLY run the first time.
eg:
if (!IsPostBack)
{
code here to load GV
}
Next up? when the GV is loaded with that data, you need to setup the combo box and the cascade. And further more, this setup of each row should occur in the row data bound event.
So, your posted code does look ok, but we missing how/when you load the GV.
And we don't see your save button either. But at this point, I would share your code that loads up the GV - this all important information is missing here.
So edit your question - show how and when you load the grid up - that's missing.
Also, why the row created event being used here to setup a event? Just put the event stub and definition in the markup.
You are free to drop in a plane jane button, or DDL or whatever into the GV. And you should wire up the events like all other controls.
So, remove that row created event stub - it might be wiring up events for the wrong row - but it not required, and is a high risk adventure.
So, just do this:
So, for a button, or DDL in the GV? You can't double click on a button (to create a click event), and you can't display the property sheet to add events. But you can in markup just type in the event name, hit "=", and note how above intel-sense pops up a option to create the event. So, add the event that way. And after you select create new event, then you can flip over to code behind - you see the new event stub, and add your code to that stub. The GV uses internal information to wire up each row events - you may well be messing this up.
So, I would remove your row added - as we don't have details about that code and how/when you add a row, but 100% elimination of the row created event, and wiring up a click event will go a long way to elimination of any issues here - this would be especially the case if your row add event "copy's" controls - you might be copy the the DDL object when you do this, and that again will cause issues. In other words you may have the same object for two rows - changes to one will effect the other.
So, dump your row add event, and add the event directly in markup for the ddl as per above.
So, for buttons on each row, or whatever? You can still (and should) use markup to add those events - not code unless no other means exists to do so.
Edit: Working example
So, say this markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID"
CssClass="table"
Width="30%" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Firstname" HeaderText="Firstname" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:TemplateField HeaderText="Select Hotel City">
<ItemTemplate>
<asp:DropDownList ID="cboCity" runat="server" Width="120px" Height="26px"
DataTextField = "City"
DataValueField = "City"
AutoPostback="true"
OnSelectedIndexChanged="cboCity_SelectedIndexChanged"
>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Select Hotel">
<ItemTemplate>
<asp:DropDownList ID="cboHotels" runat="server" Width="210px" Height="26px"
DataValueField ="ID"
DataTextField ="HotelName">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nights" >
<ItemTemplate>
<asp:TextBox ID="txtNights" runat="server" Style="text-align:right"
Text='<%# Eval("Nights") %>' Width="70px" >
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
We will cascade city combo to restrict Hotels in 2nd combo.
So, our code to load:
DataTable rstCity = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid ()
{
// load up City list for combo box - all rows (scope = page)
SqlCommand cmdSQL = new SqlCommand("SELECT City from City ORDER BY City");
rstCity = MyRstP(cmdSQL);
// load up the grid
cmdSQL.CommandText = "SELECT * from People ORDER BY FirstName";
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
We have this:
Note how we did NOT risk trying to set the DDL's in the markup - since we cascading - there will be way too many issues.
So, of course we have row data bound - and that sets up the two DDL's. (we setup the cascade AND ALSO set their values.
We have this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = (DataRowView)e.Row.DataItem; // get the row data
// load the city combo box
DropDownList cboCity = (DropDownList)e.Row.FindControl("cboCity");
cboCity.DataSource = rstCity;
cboCity.DataBind();
// add blank row for city
cboCity.Items.Insert(0, new ListItem("Select City", ""));
cboCity.SelectedValue = gData["City"].ToString(); // set value of Current city
// now load Hotel combo box - but cascade from above City cbo
string strSQL = #"Select ID, HotelName From tblHotels WHERE City = #City " +
" ORDER BY HotelName";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = gData["HotelCity"].ToString();
DropDownList cboHotels = (DropDownList)e.Row.FindControl("cboHotels");
DataTable rstHotels = MyRstP(cmdSQL);
cboHotels.DataSource = rstHotels;
cboHotels.DataBind();
cboHotels.Items.Insert(0, new ListItem("Select Hotel", ""));
// set hotels combo to current selected
cboHotels.SelectedValue = gData["Hotel_id"].ToString();
}
}
So, the only part left is the first DDL post-back and cascade code. We have this:
protected void cboCity_SelectedIndexChanged(object sender, EventArgs e)
{
// city changed, so cascade Hotel cbo
DropDownList cboCity = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)cboCity.NamingContainer;
// filter hotels to current city
string strCity = cboCity.SelectedItem.Text;
DropDownList cboHotels = (DropDownList)gRow.FindControl("cboHotels");
if (strCity != "Select City")
{
SqlCommand cmdSQL = new
SqlCommand(#"SELECT * from tblHotels WHERE City = #City ORDER BY HotelName");
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = strCity;
cboHotels.DataSource = MyRstP(cmdSQL);
cboHotels.DataBind();
cboHotels.Items.Insert(0, new ListItem("Select Hotel", ""));
}
}
So, with above? I don't see how it is possible that some "other" row gets effected here (unless you have some other code that attempts to mess around with the rows, or inserts a row into the GV. If you going to insert a row, then insert at the database level - and re-bind the GV. But, inserting is a separate issue.
So here's the update where the second dropdown now functions correctly. However, when you click the update button, it will save correctly to the DB, but resets and clears out the second drowpdown list.
Markup:
<asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="Vertical" CellPadding="4"
ItemType="GetAGrip.Models.CartItem" CssClass="table table-striped table-bordered"
EnableViewState="true">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ID" SortExpression="ProductID" />
<asp:BoundField DataField="Product.ProductName" HeaderText="Name" />
<asp:BoundField DataField="Product.UnitPrice" HeaderText="Price (each)" DataFormatString="{0:c}" />
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text="<%#: Item.Quantity %>"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Size">
<ItemTemplate>
<asp:DropDownList ID="Sizeddl" runat="server" Font-Size="Medium" OnSelectedIndexChanged="Sizeddl_SelectedIndexChanged"
AutoPostBack="true" ForeColor="Black" SelectedValue="<%#: Item.SizeName %>">
<asp:ListItem Selected="True" Text="Choose one" Value="0"></asp:ListItem>
<asp:ListItem Text="S" Value="S"></asp:ListItem>
<asp:ListItem Text="M" Value="M"></asp:ListItem>
<asp:ListItem Text="L" Value="L"></asp:ListItem>
<asp:ListItem Text="XL" Value="XL"></asp:ListItem>
<asp:ListItem Text="2XL" Value="2XL"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Color">
<ItemTemplate>
<asp:DropDownList ID="ColorNameddl" runat="server" Font-Size="Medium" ForeColor="Black">
</asp:DropDownList>
<asp:Label ID="Templbl" runat="server" Visible="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Total">
<ItemTemplate>
<%#: String.Format("{0:c}", ((Convert.ToDouble(Item.Quantity)) * Convert.ToDouble(Item.Product.UnitPrice)))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remove Item">
<ItemTemplate>
<asp:CheckBox ID="Remove" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div>
<p></p>
<strong>
<asp:Label ID="LabelSubtotal" runat="server" Text="SubTotal: "></asp:Label>
<asp:Label ID="lblSubtotal" runat="server" EnableViewState="false"></asp:Label>
</strong>
<p></p>
<strong>
<asp:Label ID="LabelTax" runat="server" Text="Tax Total: "></asp:Label>
<asp:Label ID="lblTax" runat="server" EnableViewState="false"></asp:Label>
</strong>
<p></p>
<strong>
<asp:Label ID="LabelTotalText" runat="server" Text="Order Total: "></asp:Label>
<asp:Label ID="lblTotal" runat="server" EnableViewState="false"></asp:Label>
</strong>
</div>
<br />
<table>
<tr>
<td>
<asp:Button ID="UpdateBtn" runat="server" Text="Update" OnClick="UpdateBtn_Click" Visible="false" Enabled="false"/>
</td>
<th colspan="1">&nbsp
</th>
<td>
<asp:ImageButton ID="CheckoutImageBtn" runat="server"
ImageUrl="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif"
Width="145" AlternateText="Check out with PayPal"
OnClick="CheckoutBtn_Click"
BackColor="Transparent" BorderWidth="0" />
</td>
</tr>
</table>
Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
}
using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
{
decimal cartTotal = 0;
cartTotal = usersShoppingCart.GetTotal();
if (cartTotal > 0)
{
// Display Total.
lblSubtotal.Text = String.Format("{0:c}", usersShoppingCart.GetSubtotal());
lblTax.Text = String.Format("{0:c}", usersShoppingCart.GetTax());
lblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
}
else
{
lblSubtotal.Text = "";
lblTax.Text = "";
lblTotal.Text = "";
ShoppingCartTitle.InnerText = "Shopping Cart is Empty";
UpdateBtn.Visible = false;
CheckoutImageBtn.Visible = false;
}
}
}
Load Grid, Load Second DropDown List & Hide DDLs on rows they shouldn't be on:
void LoadGrid()
{
GetShoppingCartItems();
CartList.DataSource = GetShoppingCartItems();
CartList.DataBind();
var _db = new ProductContext();
for (int i = 0; i < CartList.Rows.Count; i++)
{
DropDownList sizeDDL = CartList.Rows[i].FindControl("Sizeddl") as DropDownList;
DropDownList colorDDL = CartList.Rows[i].FindControl("ColorNameddl") as DropDownList;
var _colors = (from c in _db.Colors
select c.ColorName).Distinct().ToList();
colorDDL.DataSource = _colors;
colorDDL.DataBind();
colorDDL.Items.Insert(0, new ListItem("Select Color", "0"));
colorDDL.SelectedIndex = 0;
foreach (ListItem item in colorDDL.Items)
{
item.Attributes.Add("disabled", "disabled");
}
IOrderedDictionary rowValues = new OrderedDictionary();
rowValues = GetValues(CartList.Rows[i]);
var _prodID = Convert.ToInt32(rowValues["ProductID"]);
var _prod = (from c in _db.Products
where c.ProductID == _prodID
select c.CategoryID).FirstOrDefault();
if (_prod != 1)
{
sizeDDL.Visible = false;
colorDDL.Visible = false;
}
}
}
GetShoppingCartItems Method:
public List<CartItem> GetShoppingCartItems()
{
ShoppingCartActions actions = new ShoppingCartActions();
return actions.GetCartItems();
}
UpdateCartItems Method
public List<CartItem> UpdateCartItems()
{
using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
{
String cartId = usersShoppingCart.GetCartId();
ShoppingCartActions.ShoppingCartUpdates[] cartUpdates = new ShoppingCartActions.ShoppingCartUpdates[CartList.Rows.Count];
for (int i = 0; i < CartList.Rows.Count; i++)
{
IOrderedDictionary rowValues = new OrderedDictionary();
rowValues = GetValues(CartList.Rows[i]);
cartUpdates[i].ProductId = Convert.ToInt32(rowValues["ProductID"]);
CheckBox cbRemove = new CheckBox();
cbRemove = (CheckBox)CartList.Rows[i].FindControl("Remove");
cartUpdates[i].RemoveItem = cbRemove.Checked;
TextBox quantityTextBox = new TextBox();
quantityTextBox = (TextBox)CartList.Rows[i].FindControl("PurchaseQuantity");
cartUpdates[i].PurchaseQuantity = Convert.ToInt16(quantityTextBox.Text.ToString());
DropDownList sizeDropDown = new DropDownList();
sizeDropDown = (DropDownList)CartList.Rows[i].FindControl("Sizeddl");
cartUpdates[i].SizeName = sizeDropDown.Text;
DropDownList colorDropDown = new DropDownList();
colorDropDown = (DropDownList)CartList.Rows[i].FindControl("ColorNameddl");
cartUpdates[i].ColorName = colorDropDown.Text;
}
usersShoppingCart.UpdateShoppingCartDatabase(cartId, cartUpdates);
CartList.DataBind();
lblSubtotal.Text = String.Format("{0:c}", usersShoppingCart.GetSubtotal());
lblTax.Text = String.Format("{0:c}", usersShoppingCart.GetTax());
lblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
return usersShoppingCart.GetCartItems();
}
}
GetValues Dictionary
public static IOrderedDictionary GetValues(GridViewRow row)
{
IOrderedDictionary values = new OrderedDictionary();
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.Visible)
{
// Extract values from the cell.
cell.ContainingField.ExtractValuesFromCell(values, cell, row.RowState, true);
}
}
return values;
}
Update Button Click
protected void UpdateBtn_Click(object sender, EventArgs e)
{
for (int i = 0; i < CartList.Rows.Count; i++)
{
UpdateCartItems();
}
Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
RowDataBound
protected void CartList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = (DataRowView)e.Row.DataItem; // get row data.
// load the color Drop Down List.
DropDownList sizeDDL = (DropDownList)e.Row.FindControl("Sizeddl");
sizeDDL.SelectedValue = gData["SizeName"].ToString();
//// Load Color DDL
var _size = sizeDDL.SelectedItem.Text;
int _prod = Convert.ToInt32(e.Row.Cells[0].Text);
var _db = new ProductContext();
var qryColor = (from p in _db.ProductAttributes
join c in _db.Colors
on p.ColorID equals c.ColorID
where p.SizeName == _size & p.ProductID == _prod
select new { p.ColorID, c.ColorName }).Distinct().ToList();
DropDownList colorDDL = (DropDownList)e.Row.FindControl("ColorNameddl");
// Bind Color Drop Down List to DataTable.
foreach (ListItem item in colorDDL.Items)
{
if (qryColor.Any(c => c.ColorName == item.ToString()))
{
item.Enabled = true;
}
}
colorDDL.SelectedValue = gData["ColorName"].ToString();
}
}
1st Dropdown SelectedIndexChanged
protected void Sizeddl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList sizeDDL = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)sizeDDL.NamingContainer;
string strSize = sizeDDL.SelectedItem.Text;
DropDownList colorDDL = (DropDownList)gRow.FindControl("ColorNameddl");
if (strSize != "Choose one")
{
using (ProductContext context = new ProductContext())
{
int _prodID = Convert.ToInt32(gRow.Cells[0].Text);
var _size = sizeDDL.SelectedItem.Text;
var qryColor = (from p in context.ProductAttributes
join c in context.Colors
on p.ColorID equals c.ColorID
where p.SizeName == _size & p.ProductID == _prodID
select new { p.ColorID, c.ColorName }).Distinct().ToList();
if (qryColor.Count > 0)
{
foreach (ListItem item in colorDDL.Items)
{
if (qryColor.Any(c => c.ColorName == item.ToString()))
{
item.Enabled = true;
}
else
{
item.Enabled = false;
}
}
colorDDL.Items[0].Enabled = true;
colorDDL.Enabled = true;
colorDDL.SelectedIndex = 0;
}
else
{
colorDDL.SelectedIndex = 0;
colorDDL.Enabled = false;
}
}
}
}
Anyplace you see a method that is not above, it's because it's a method in my Logic file to handle database queries for the whole application.

How to fetch the Checkbox List inserted values in database back to the checkbox list

I build a demo application in which I used a checkbox list to get the hobbies and enter those values in the database as follows:
The ASP code for checkbox list is:
<asp:CheckBoxList ID="chkboxlsthobbies" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>cricket</asp:ListItem>
<asp:ListItem>football</asp:ListItem>
<asp:ListItem>pool</asp:ListItem>
<asp:ListItem>basketball</asp:ListItem>
<asp:ListItem>rugby</asp:ListItem>
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" Text="submit" OnClick="Button1_Click" />
And the corresponding C# code to enter that value in database is as follows:
protected void Button1_Click(object sender, EventArgs e)
{
string str = string.Empty;
foreach (ListItem item in chkboxlsthobbies.Items)
{
if (item.Selected)
{
str += string.Format("{0}, ", item.Text);
}
}
SqlCommand cmd = new SqlCommand("insert into [CheckboxTable] values('" + str + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
bindgrid();
}
Now I am using a Gridview to bind that table data and display it and in that, I am having a onRowEditing and onRowDeleting event.
The Gridview code is as follows:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="gvtxtedit" runat="server" CommandName="Edit" Text="Edit" />
<asp:Button ID="gvtxtdelete" runat="server" CommandName="Delete" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hobbies">
<ItemTemplate>
<asp:Label ID="gvlblfirstname" runat="server" Text='<%#Eval("Hobbies") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the Gridview bind method is as follows:
protected void bindgrid()
{
SqlCommand cmd = new SqlCommand("select * from [CheckboxTable]", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
And now I am completely stuck in this problem generally I am able to fetch the value of any field back to TextBox or a Dropdown list on the form
Example:
txtfirstname.Text = dt.Rows[0]["firstname"].ToString();
inside the onRowEditing event to fetch the field value back to the control on the form, which I can do for textbox and dropdown.
The problem is I am not able to figure out that how to fetch the multiple values separated by a "," back to a checkbox list, because there are multiple values, I have been trying this for a long time.
Final problem is that fetch the values in database back to the checkbox list inside the onRowEditing event of GridView.
I wrote this onRowEditing Gridview function to implement the above functionality i.e: to fetch the checkbox list values saved in database back to the checkbox list on the form inside the onRowEditing event of Gridview
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
chkboxlsthobbies.ClearSelection();
//Get the ID
int id = Int32.Parse(GridView1.DataKeys[Int32.Parse(e.NewEditIndex.ToString())].Values["ID"].ToString());
SqlCommand cmd = new SqlCommand("select * from CheckboxTable where ID = '"+id+"'", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
// Get the exact column and save it in a string.
string str = dt.Rows[0]["Hobbies"].ToString();
string[] strlist = str.Split(',').Select(t => t.Trim()).ToArray(); //Split into array and trim it.
//Finally the main functionality to check the values in checkbox list.
foreach (string s in strlist)
{
foreach (ListItem item in chkboxlsthobbies.Items)
{
if (item.Value == s)
{
item.Selected = true;
break;
}
}
}
Thank You.

Session Variables not being seen/used

I have an aspx page that displays a gridview of questions waiting on review with 10 questions shown per page. If a question is selected it is opened in a new page where the reviewer can either submit a review or cancel and return to the list of questions needing review.
Currently this works fine, but have a request from the reviewers so that if they are on page 4 of the gridview when they go to a question, they get returned to page 4 if they hit cancel and return to the list of questions (currently they are returned to page 1).
So I am setting a couple session variables to capture the question selected and to capture the pageindex of the gridview control for future use. Trying to use the session variable for the questionId on the page load of the detail page, but it is not being passed. On returning to the Review List page the pageindex that is being set on the gridview is always 0, not the session variable.
Updated Gridview control (note two controls, one hyperlink(which should go away once the other linkbutton control works):
<asp:GridView ID="GridView1" runat="server" Caption="Questions Awaiting Review" AllowSorting="True" PagerSettings-Mode="NumericFirstLast" OnPageIndexChanging="GridView1_PageIndexChanging"
CaptionAlign="Top" EmptyDataText="No Questions Pending Review." PageSize="10" AllowPaging="true" PagerStyle-HorizontalAlign="Center" PagerStyle-Font-Size="Large" DataKeyNames="QuestionID"
AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="250" />
<asp:BoundField DataField="SubmitDate" HeaderText="Submitted Date" ItemStyle-Width="60" />
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="Details" runat="server" NavigateUrl='<%#"~/Review/ReviewDetail.aspx?Id=" + Eval("QuestionID") +"&PageIndex=" + GridView1.PageIndex %>'>View Question</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Details2" runat="server" Text="Session" OnClick="Session_OnClick"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
OnClick Event for the second button:
protected void Session_OnClick(object sender, EventArgs e)
{
Session["PageIndex"] = GridView1.PageIndex;
Session["QuestionId"] = GridView1.SelectedDataKey;
Response.Redirect("~/Review/ReviewDetail.aspx", false;
}
Connection string on the detail page which is now not getting a value for the parameter "QuestionID"; ):
SqlCommand command = new SqlCommand("QuestionDetail", Conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#QuestionID", SqlDbType.BigInt));
command.Parameters["#QuestionID"].Value = Convert.ToInt64(Session["QuestionId"]);
Conn.Open();
SqlDataReader reader = command.ExecuteReader();
PageLoad and gridview binding on the ReviewList page that should be using session variable to set page of grid control, but is always going to default of page 0:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridView();
}
else
{
if (Convert.ToInt32(Session["PageIndex"]) !=0)
{
GridView1.PageIndex = Convert.ToInt32(Session["PageIndex"]);
bindGridView();
}
}
}
private void bindGridView()
{
string connectionString = WebConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
string selectSQL = String.Format("Select QuestionID, KeyObjective, SubmitDate from Questions where Author <> '{0}' and QuestionID not in(Select QuestionID from Review where Reviewer = '{0}')", User.Identity.Name);
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Review");
GridView1.DataSource = ds;
GridView1.DataBind();
}
Your error probably means that Request["Id"] is empty or does not exists. Always check if QueryStrings exist and do the conversions of user inputs that are likely to fail inside a try-catch block.
protected void Page_Load(object sender, EventArgs e)
{
long QuestionID = -1;
//check if the Id QueryString exists
if (Request.QueryString["Id"] != null)
{
//try to convert to int64
try
{
QuestionID = Convert.ToInt64(Request.QueryString["Id"]);
}
catch
{
}
}
//if valid QuestionID
if (QuestionID >= 0)
{
using (SqlConnection connection = new SqlConnection(Common.connectionString))
using (SqlCommand command = new SqlCommand("QuestionDetail", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#QuestionID", SqlDbType.BigInt).Value = QuestionID;
//try to execute the stored procedure
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
//handle sql error
Literal1.Text = ex.Message;
}
}
}
}
And why do you do a PostBack on the first button? That is not needed just to redirect to a different url. Change it to:
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#"~/Review/ReviewDetail.aspx?Id=" + Eval("QuestionID") %>'>View Question</asp:HyperLink>
Or with the Page Index also in the QueryString:
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#"~/Review/ReviewDetail.aspx?Id=" + Eval("QuestionID") + "&Page=" + GridView2.PageIndex %>'>View Question</asp:HyperLink>
UPDATE
If you really want to do a PostBack to set the Sessions you can use the OnRowCommand:
<asp:LinkButton ID="LinkButton1" CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="viewQuestion">View Question</asp:LinkButton>
CS
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "viewQuestion")
{
Session["PageIndex"] = GridView1.PageIndex;
Session["QuestionId"] = e.CommandArgument.ToString();
Response.Redirect("~/Review/ReviewDetail.aspx?Id=" + Convert.ToString(Session["QuestionId"]));
}
}

How do I show an associated value with a dropdown list item (after choosing it from the list)?

I am programming in ASP.NET, visual studio. I have a dropdown list created in HTML form. If I dropdown the list, it displays the record from associated column in the table. But what I want is to show the corresponding value / record with that list item.
For example in the table, I have column id, productname and price. After choosing a particular product name (from drop down list), the associated price with it must be displayed in front of it (in a label).
However, By default, I want the drop down list to shows nothing in the beginning.
UPDATE:
Store.aspx:
<form id="form1" runat="server">
<div>
Welcome
<asp:Label ID="Label3" runat="server" ></asp:Label>
<br />
<br />
Products: <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" ></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [productdata]"></asp:SqlDataSource>
Price:
<asp:Label ID="Label1" runat="server" ></asp:Label>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Add to Cart" />
<br />
<br />
Items in cart: <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
<br />
<br />
Total Price: <asp:Label ID="Label2" runat="server"></asp:Label>
</div>
</form>
Store.aspx.cs:
public partial class Store : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label3.Text = Request.QueryString["name"];//show welcome text
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
if (!IsPostBack)
{
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata", sc);
sc.Open();
DropDownList1.DataTextField = "productname";//show in the dropdown list
DropDownList1.DataValueField = "price"; //show in the label
DropDownList1.DataSource = sqlcom.ExecuteReader();
DropDownList1.DataBind();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlDataReader rd;
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata where id=" + Convert.ToUInt32(DropDownList1.SelectedValue), sc);
sc.Open();
rd = sqlcom.ExecuteReader();
if (rd.Read())
{
Label1.Text = rd[2].ToString();
}
sc.Close();
}
}
}
Database:
CREATE TABLE [dbo].[productdata] (
[Id] INT NOT NULL,
[productname] VARCHAR (50) NULL,
[price] FLOAT (53) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
This Edit according to using AutoPostBack=True and if (!IsPostBack) in Page_Load thanks to Arindam:
For simply solution using postback event:
First you should add OnSelectedIndexChanged event for dropdownlist
<asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="GetPrice" AutoPostBack="true">
</asp:DropDownList>
Then in code behind you just get selected value and fill to the label price
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label3.Text = Request.QueryString["name"];//show welcome text
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata", sc);
sc.Open();
DropDownList1.DataTextField = "productname";//show in the dropdown list
DropDownList1.DataValueField = "price"; //show in the label
DropDownList1.DataSource = sqlcom.ExecuteReader();
DropDownList1.DataBind();
}
}
}
protected void GetPrice(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedValue;
}
You have to use AutoPostBack=True so that when you change index of dropdownlist, it will trigger a postback to server so the function GetPrice(...) will be called.
Every time the page postback, it will call function Page_Load(...) first, so you must use propertive IsPostBack to check if case1_this is the first time the page is loaded, or case2_a postback event, and you only set the ddl datasource at case1 because if you set datasource, by default the dropdownlist will reset to select first item in list.
When you go advance, you should consider using Javascript and Jquery to solve this, so the page will not load again like this postback solution.
And one more thing, you should name your controls well, don't make them default like that. It's one of two hard things in programming.
Yes you can but if not please use datatable and i am sure that work fine .if u not able do that just post I will give the correction.

Categories

Resources