I have a Formview that gets populated with SQL data when a dropdown is selected, but when I click edit, it wants to edit the first item on the dropdown list, because technically it still thinks its on the first page. I want the paging to be linked to the drop down but I'm not exactly sure how to accomplish this. I have a many fields so I won't post the full Formview but here's the key parts.
Formview Item Template:
<ItemTemplate>
<table id="FormTable">
<tr><th>
<asp:DropDownList ID="ProjectNameDropDown" runat="server" AutoPostBack="true"
DataSourceID="SqlDataSource1"
DataValueField="Project_Name" name="Text" OnSelectedIndexChanged="ProjectSelect" AppendDataBoundItems="true">
<asp:ListItem Text="Select a Project" />
</asp:DropDownList>
<asp:Panel ID="Panel1" runat="server" Visible="false">
</th>
<th>
<asp:Button ID="EditButton" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit" />
<asp:Button ID="DeleteButton" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" />
<asp:Button ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</th></tr>
<tr><th>
Business Category:
</th><td>
<asp:Label ID="BusinessCategoryLabel" runat="server"
Text='<%# Bind("Business_Category") %>'
/>
</td></tr>
<tr><th>
Project Description:
</th><td>
<asp:TextBox ID="ProjectDescriptionLabel" runat="server" ReadOnly="true"
Text='<%# Bind("Project_Description") %>' TextMode="MultiLine" Rows="5" />
</td></tr>
<tr><th>
Operations Owner:
</th><td>
<asp:Label ID="OwnerLabel" runat="server"
Text='<%# Bind("Operations_Owner") %>' />
</td></tr>
Code Behind:
protected void ProjectSelect(object sender, EventArgs e)
{
DropDownList ProjectNameDropDown = (DropDownList)FormView1.FindControl("ProjectNameDropDown");
Panel Panel1 = (Panel)FormView1.FindControl("Panel1");
Label BusinessCategoryLabel = (Label)FormView1.FindControl("BusinessCategoryLabel");
TextBox ProjectDescriptionLabel = (TextBox)FormView1.FindControl("ProjectDescriptionLabel");
Label OwnerLabel = (Label)FormView1.FindControl("OwnerLabel");
Label StakeholderLabel = (Label)FormView1.FindControl("StakeholderLabel");
Label ReqOrgLabel = (Label)FormView1.FindControl("ReqOrgLabel");
Label PriorityLabel = (Label)FormView1.FindControl("PriorityLabel");
Label DateInitiatedLabel = (Label)FormView1.FindControl("DateInitiatedLabel");
Label ReqCompletionDateLabel = (Label)FormView1.FindControl("ReqCompletionDateLabel");
Label ProjectLOELabel = (Label)FormView1.FindControl("ProjectLOELabel");
Label OELabel = (Label)FormView1.FindControl("OELabel");
Label PELabel = (Label)FormView1.FindControl("PELabel");
Label EMLabel = (Label)FormView1.FindControl("EMLabel");
Label PARCHLabel = (Label)FormView1.FindControl("PARCHLabel");
Label WindowsLabel = (Label)FormView1.FindControl("WindowsLabel");
Label StorageLabel = (Label)FormView1.FindControl("StorageLabel");
Label NetworkLabel = (Label)FormView1.FindControl("NetworkLabel");
Label Unix2Label = (Label)FormView1.FindControl("Unix2Label");
Label TSGLabel = (Label)FormView1.FindControl("TSGLabel");
Label SANDLabel = (Label)FormView1.FindControl("SANDLabel");
Label MOPSLabel = (Label)FormView1.FindControl("MOPSLabel");
Label ACSROpsLabel = (Label)FormView1.FindControl("ACSROpsLabel");
Label IMOpsLabel = (Label)FormView1.FindControl("IMOpsLabel");
Label OSCOpsLabel = (Label)FormView1.FindControl("OSCOpsLabel");
Label FinancialSvcsLabel = (Label)FormView1.FindControl("FinancialSvcsLabel");
Label VantageLabel = (Label)FormView1.FindControl("VantageLabel");
Label VoiceSysOpsLabel = (Label)FormView1.FindControl("VoiceSysOpsLabel");
Label VoiceAppOpsLabel = (Label)FormView1.FindControl("VoiceAppOpsLabel");
Label ACPxOpsLabel = (Label)FormView1.FindControl("ACPxOpsLabel");
Label WFXOpsLabel = (Label)FormView1.FindControl("WFXOpsLabel");
Label WebOpsLabel = (Label)FormView1.FindControl("WebOpsLabel");
Label DBALabel = (Label)FormView1.FindControl("DBALabel");
Label CapacityPlanningLabel = (Label)FormView1.FindControl("CapacityPlanningLabel");
Label BCPLabel = (Label)FormView1.FindControl("BCPLabel");
Label DataCenterLabel = (Label)FormView1.FindControl("DataCenterLabel");
Label GoldsmithLabel = (Label)FormView1.FindControl("GoldsmithLabel");
Label AmericasITOpsLabel = (Label)FormView1.FindControl("AmericasITOpsLabel");
Label APACITOpsLabel = (Label)FormView1.FindControl("APACITOpsLabel");
Label EMEAITOpsLabel = (Label)FormView1.FindControl("EMEAITOpsLabel");
Panel1.Visible = true;
if (ProjectNameDropDown.Items.FindByText("Select a Project").Selected != true)
{
string myConnectionString = #"Data Source=odcsgwinsql11.devcsg.com\ss2008;Initial Catalog=hulc01;Integrated Security=True";
SqlConnection myConnection = new SqlConnection(myConnectionString);
string MySelectQuery = "SELECT * FROM Common WHERE Project_Name = '" + ProjectNameDropDown.SelectedValue + "'";
using (SqlCommand cmd = new SqlCommand(MySelectQuery))
{
cmd.Connection = myConnection;
myConnection.Open();
SqlDataAdapter Adapter1 = new SqlDataAdapter(cmd);
DataSet dset = new DataSet();
Adapter1.Fill(dset);
BusinessCategoryLabel.Text = dset.Tables[0].Rows[0]["Business_Category"].ToString();
ProjectDescriptionLabel.Text = dset.Tables[0].Rows[0]["Project_Description"].ToString();
OwnerLabel.Text = dset.Tables[0].Rows[0]["Operations_Owner"].ToString();
StakeholderLabel.Text = dset.Tables[0].Rows[0]["NonOps_Key_Stakeholder"].ToString();
ReqOrgLabel.Text = dset.Tables[0].Rows[0]["Requesting_Organization"].ToString();
PriorityLabel.Text = dset.Tables[0].Rows[0]["Priority"].ToString();
DateInitiatedLabel.Text = dset.Tables[0].Rows[0]["Date_Initiated"].ToString();
ReqCompletionDateLabel.Text = dset.Tables[0].Rows[0]["Required_Completion_Date"].ToString();
ProjectLOELabel.Text = dset.Tables[0].Rows[0]["Project_LOE"].ToString();
OELabel.Text = dset.Tables[0].Rows[0]["OE"].ToString();
PELabel.Text = dset.Tables[0].Rows[0]["PE"].ToString();
EMLabel.Text = dset.Tables[0].Rows[0]["EM"].ToString();
PARCHLabel.Text = dset.Tables[0].Rows[0]["PARCH"].ToString();
WindowsLabel.Text = dset.Tables[0].Rows[0]["Windows"].ToString();
StorageLabel.Text = dset.Tables[0].Rows[0]["Storage"].ToString();
NetworkLabel.Text = dset.Tables[0].Rows[0]["Network"].ToString();
Unix2Label.Text = dset.Tables[0].Rows[0]["UNIX2"].ToString();
TSGLabel.Text = dset.Tables[0].Rows[0]["TSG"].ToString();
SANDLabel.Text = dset.Tables[0].Rows[0]["SAND"].ToString();
MOPSLabel.Text = dset.Tables[0].Rows[0]["MOPS"].ToString();
ACSROpsLabel.Text = dset.Tables[0].Rows[0]["ACSR_Ops"].ToString();
IMOpsLabel.Text = dset.Tables[0].Rows[0]["IM_Ops"].ToString();
OSCOpsLabel.Text = dset.Tables[0].Rows[0]["OSC_Ops"].ToString();
FinancialSvcsLabel.Text = dset.Tables[0].Rows[0]["Financial_Svcs"].ToString();
VantageLabel.Text = dset.Tables[0].Rows[0]["Vantage"].ToString();
VoiceAppOpsLabel.Text = dset.Tables[0].Rows[0]["Voice_Sys_Ops"].ToString();
VoiceSysOpsLabel.Text = dset.Tables[0].Rows[0]["Voice_App_Ops"].ToString();
ACPxOpsLabel.Text = dset.Tables[0].Rows[0]["ACPX_Ops"].ToString();
WFXOpsLabel.Text = dset.Tables[0].Rows[0]["WFX_Ops"].ToString();
WebOpsLabel.Text = dset.Tables[0].Rows[0]["Web_Ops"].ToString();
DBALabel.Text = dset.Tables[0].Rows[0]["DBA"].ToString();
CapacityPlanningLabel.Text = dset.Tables[0].Rows[0]["Capacity_Planning"].ToString();
BCPLabel.Text = dset.Tables[0].Rows[0]["BCP"].ToString();
DataCenterLabel.Text = dset.Tables[0].Rows[0]["Data_Center"].ToString();
GoldsmithLabel.Text = dset.Tables[0].Rows[0]["Goldsmith"].ToString();
AmericasITOpsLabel.Text = dset.Tables[0].Rows[0]["Americas_IT_Ops"].ToString();
APACITOpsLabel.Text = dset.Tables[0].Rows[0]["APAC_IT_Ops"].ToString();
EMEAITOpsLabel.Text = dset.Tables[0].Rows[0]["EMEA_IT_Ops"].ToString();
}
}
I imagine somehow telling the Formview what page to switch to when selecting from the dropdown but I haven't been able to figure out the coding for that. Thanks for your help!
One way to do this (the way I've done it in the past) would be to move your databound DropDownList outside of the FormView. Then, bind your FormView to a different SQLDataSource that's dependent on the DropDownLists SelectedValue. So you would have a DDL with all your Project Names:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource1" DataTextField="Project_Name"
DataValueField="Project_Name">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Your Connection String"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT DISTINCT [Project_Name] FROM [ProjectTable]">
</asp:SqlDataSource>
AND a FormView that is dependent upon what is selected in the DDL:
<asp:FormView ID="FormView1" runat="server" AllowPaging="True"
DataKeyNames="Project_Name" DataSourceID="SqlDataSource2">
...
</asp:FormView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="Your Connection String"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT * FROM [ProjectTable] WHERE Project_Name=#Project_Name">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="Project_Name"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
This way, when you click the "Edit" button in your FormView, you are editing the record you intended to edit.
As a side-note, your Code Behind leaves you very vulnerable to SQL Injection. I'd be careful about that. Instead of using string concatenation to generate that SELECT query, you should use Parameterized queries
Related
I can't getting the DataValueField setting on Drop Down List on Edit Item Template in c# .
I need update the row of GridView opening new aspx page in window popup where get the ID selected from DB MySQL.
I have this error :
Object reference not set to an instance of an object
in this code-behind line :
string taskID = ddlID.DataValueField;
Can you help me ?
My code below, thank you in advance for any help, really appreciated.
.cs
protected void ddlID_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlID = new DropDownList();
ddlID = (DropDownList)FindControl("ddlID");
string taskID = ddlID.DataValueField;
string queryString = "newPage.aspx?membershipId=" + taskID.ToString().ToUpper();
string newWin = "var Mleft = (screen.width/2)-(1200/2);
var Mtop = (screen.height/2)-(700/2);
window.open('" + queryString + "','_blank','height=600,width=900,
status=yes,
toolbar=no,scrollbars=yes,menubar=no,
location=no,top=\'+Mtop+\', left=\'+Mleft+\';');";
ClientScript.RegisterStartupScript(this.GetType(), "pop", newWin, true);
}
.aspx
<asp:TemplateField>
<EditItemTemplate>
<asp:DropDownList ID="ddlID" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="ddlID_SelectedIndexChanged"
BackColor="Yellow" DataValueField='<%# Eval("ID")%>'>
<asp:ListItem Text="--------------" Value=""></asp:ListItem>
<asp:ListItem Text="Update Name" Value="1"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
#Edit01
<asp:TemplateField>
<EditItemTemplate>
<asp:DropDownList ID="ddlID" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="ddlID_SelectedIndexChanged"
BackColor="Yellow" DataValueField="ID">
<asp:ListItem Text="--------------" Value=""></asp:ListItem>
<asp:ListItem Text="Update Name" Value="1"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
protected void ddlID_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlID = new DropDownList();
string taskID = ddlID.SelectedValue;
string queryString = "newPage.aspx?membershipId=" + taskID.ToString().ToUpper();
string newWin = "var Mleft = (screen.width/2)-(1200/2);
var Mtop = (screen.height/2)-(700/2);
window.open('" + queryString + "','_blank','height=600,width=900,
status=yes,
toolbar=no,scrollbars=yes,menubar=no,
location=no,top=\'+Mtop+\', left=\'+Mleft+\';');";
ClientScript.RegisterStartupScript(this.GetType(), "pop", newWin, true);
}
Your DropDownList is in EditTemplate of GridView so you have to get it from sender:
DropDownList ddlID = sender as DropDownList;
string taskID = ddlID.DataValueField;
Framework: ASP.NET 4.5 | Database: MSMMS
My demo application is supposed to populate textboxes with dynamic data when a selection is made from a dropdown list. I've added a button, that when pressed fires, an OnClick event that is supposed to assign values from the DB to the appropriate textboxes. Right now my code looks like:
protected void btnChoose_Click(object sender, EventArgs e)
{
API_DatabaseEntities1 db = new API_DatabaseEntities1();
var customer = (from c in db.Customers
where c.CustomerID == 4
select c).FirstOrDefault();
if (customer == null)
{
return;
}
if (ddlCustomer.SelectedValue == "Marisol") {
tbDescription.Text = customer.ToString();
tbFName.Text = customer.Fname;
tbSocial.Text = customer.SSN;
tbDOB.Text = customer.DOB.ToString();
tbFName1.Text = customer.Fname;
tbMName.Text = customer.Mname;
tbLName.Text = customer.Lname;
tbPrimaryPhone.Text = customer.PrimaryPhone;
tbSecondaryPhone.Text = customer.SecondaryPhone;
tbAdd1.Text = customer.Address;
tbCity.Text = customer.City;
tbZip.Text = customer.Zip;
tbEmail.Text = customer.Email;
tbMonLease.Text = customer.MortLeaseAmt;
tbEmployer.Text = customer.Employer;
tbPosition.Text = customer.Position;
tbHireDate.Text = customer.HireDate.ToString();
tbWorkPhone.Text = customer.WorkPhone;
tbGross.Text = customer.GrossIncome;
}
Debug.WriteLine(tbPosition.Text);
}
When the button is clicked, the page sends a request to the DB, but the textboxes remain blank. I am returning a value from the database, but it's not populating. Here is some code from my front page:
<form id="form1" runat="server">
<asp:DropDownList ID="ddlCustomer" runat="server" DataSourceID="SqlDataSource1" DataTextField="Fname" DataValueField="CustomerID"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:APIConnectionString %>" SelectCommand="SELECT [CustomerID], [Fname], [Lname] FROM [Customer] ORDER BY [Fname]"></asp:SqlDataSource><br /><br />
<asp:Button ID="btnChoose" runat="server" Text="Choose Test Case" OnClick="btnChoose_Click" /><br /><br />
Description of Goods and/or Services:<asp:TextBox ID="tbDescription" runat="server"></asp:TextBox><br /><br />
<div>
Membership #:<asp:TextBox ID="tbMembership" runat="server"></asp:TextBox> Ext.: <asp:TextBox ID="tbExt1" runat="server"></asp:TextBox>
First Name:<asp:TextBox ID="tbFName" runat="server"></asp:TextBox><br /> <br /><br />
Soc Sec No.: <asp:TextBox ID="tbSocial" runat="server"></asp:TextBox> Date of Birth:<asp:TextBox ID="tbDOB" runat="server" ></asp:TextBox>
</div><br /> <br />
I'm not sure if the problem is from the code behind or from the front page design. Any help would be appreciate. Thank you.
It looks like your code is checking for a selection in the drop-down list of the name "Marisol" - however, the "Value" field of the drop-down list is configured to use the CustomerID column. So this code populating the fields will never execute.
Maybe you should instead be using ddlCustomer.SelectedValue in the WHERE clause of your query.
I have a repeater that I populate from a database:
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"SELECT CommunityName, CID, Budget FROM Donation WHERE Year = year(getdate()) ORDER BY CommunityName", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
myRep.ItemDataBound += new RepeaterItemEventHandler(myRep_ItemDataBound);
myRep.DataSource = myDataSet;
myRep.DataBind();
}
void myRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var textbox = e.Item.FindControl("community");
textbox.ClientIDMode = ClientIDMode.Static;
textbox.ID = "community" + (e.Item.ItemIndex + 1);
}
Repeater:
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="community" Text='<%# Eval("Budget") %>' CssClass="form-control" />
</div>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
This creates 6 textboxes with labels and values, now my question is how do I detect which of these boxes belongs to the record it was initially pulled from in the database? I want to be able to modify the value in these boxes and hit a button to save them back to the database but I can't seem to wrap my head around getting them to the proper records.
Should I set the ID of the textbox to something I can parse through and match with the proper record? In the ItemDataBound?
You have to put a hidden field inside the repeater item template that takes the value from budget, and another hidden field to keep the CID value that has to be read in the post back request. Of course you need also a button and its click event handler.
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="txtBudget" Text='<%# Eval("Budget") %>' CssClass="form-control" />
<asp:HiddenField runat="server" ID="hdOriginalBudget" Value='<%# Eval("Budget") %>' />
<asp:HiddenField runat="server" ID="hdCID" Value='<%# Eval("CID") %>' />
</div>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btn" runat="server" OnClick="btn_Click" />
In your code behind you need to loop inside the repeater to check whether the text box has been changed by comparing its value to the hidden field. After you save the budget value in the database you need to realign the hidden field value to the the new value entered by the user, otherwise you will always save that value after each post back:
protected void btn_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in myRep.Items)
{
var txtBudget = item.FindControl("txtBudget") as TextBox;
var hdOriginalBudget = item.FindControl("hdOriginalBudget") as HiddenField;
var hdCID = item.FindControl("hdCID") as HiddenField;
if (txtBudget.Text != hdOriginalBudget.Value)
{
//If you enter here means the user changed the value of the text box
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"UPDATE Donation SET Budget = #Budget WHERE CID = #CID", conn);
cmd.Parameters.Add(new SqlParameter("#Budget", int.Parse(txtBudget.Text)));
cmd.Parameters.Add(new SqlParameter("#CID", int.Parse(hdCID.Value)));
conn.Open();
cmd.ExecuteNonQuery();
}
//After you write in the database realign the values
hdOriginalBudget.Value = txtBudget.Text;
}
}
}
Take care that my code is missing the most basic validation, so if the user writes an invalid value in the textbox (for example "yyy") it breaks. So please don't put it in production as it is!
I am creating the update button for the cart system in asp.net. What am I trying to do is to allow user key in the quantity items and then click the update button. Here is the design of the shopping cart system...
Unfortunately the update button doesn't work properly after the first row. I have debugged the problem and the for loop inside the btn_update_Click method returns the value of zero.
Is there any other way to overcome the problem? Thanks
Here is the source code:
<b><asp:Label ID="lbl_showResult" runat="server" Text=""></asp:Label></b>
<asp:GridView ID="grv_cart" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataSourceID="sds_store" ShowHeader="True" GridLines="None" CssClass="table">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a class="hyp_productimage imgLiquidFill imgLiquid productImage img-responsive" href='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'>
<img src='<%#Eval("image") %>' />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:Hyperlink ID="hyp_productname" Text='<%# Eval("product_name") %>' runat="server" NavigateUrl='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'></asp:Hyperlink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txt_productQuantity" Text='<%# Eval("product_quantity") %>' CssClass="form-control" runat="server" Width="60" MaxLength="5"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_update" Text="Update" runat="server" CommandArgument='<%# Eval("id") %>' CssClass="btn btn-warning" OnClick="btn_update_Click" />
<asp:Button ID="btn_remove" Text="Delete" runat="server" CommandArgument='<%# Eval("id") %>' CssClass="btn btn-danger" onclick="btn_remove_Click"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cost">
<ItemTemplate>
<asp:Hyperlink ID="hyp_productcost" Text='<%#"$"+Eval("product_cost") %>' runat="server" NavigateUrl='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'></asp:Hyperlink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sds_store" runat="server"
ConnectionString="<%$ ConnectionStrings:websiteConnection %>"
SelectCommand="SELECT [id], [product_id], [product_name], [product_cost], [product_description], [product_quantity], [image], [date] FROM [tbl_cart] WHERE [name] = #username AND [visible] = #visible">
<SelectParameters>
<asp:sessionparameter sessionfield="login" Name="username" />
<asp:Parameter Name="visible" Type="string" DefaultValue="true" />
</SelectParameters>
</asp:SqlDataSource>
<h4><asp:Label ID="lbl_totalCost" Text="" runat="server" CssClass="pull-right"></asp:Label></h4>
<br /><br /><br />
<asp:Button ID="btn_buy" Text="Buy Now" runat="server" CssClass="btn btn-success btn-lg pull-right" OnClick="btn_buy_Click" />
Here's another source code for the .cs:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace websiteEcom
{
public partial class cart : System.Web.UI.Page
{
// Open the connection for the sql
private static SqlConnection conn;
private static SqlCommand command;
protected void Page_Load(object sender, EventArgs e)
{
// Create an instance for the connection of database
string connectionString = ConfigurationManager.ConnectionStrings["websiteConnection"].ToString();
conn = new SqlConnection(connectionString);
command = new SqlCommand("", conn);
// Checks how many items are there inside the cart database and display it to the label
CheckHowManyItem();
// Multiply all the sums of the cost
lbl_totalCost.Text = "Total Cost: $"+TotalProductCost().ToString();
}
// Checks how many items are there inside the cart database and display it to the label
public void CheckHowManyItem()
{
try
{
conn.Open();
// Retrieve the number of rows from the database
string query = string.Format("SELECT COUNT(*) FROM tbl_cart WHERE name = '{0}' AND visible = '{1}'", Session["login"], "true");
command.CommandText = query;
int numberOfItems = (int)command.ExecuteScalar();
// If the number of rows is zero
if (numberOfItems == 0)
{
lbl_showResult.Text = "You have no items inside the cart.";
btn_buy.Visible = false;
}
else
{
// If there is number of rows inside
lbl_showResult.Text = "There are currently " + numberOfItems + " inside the cart.";
btn_buy.Visible = true;
}
}
finally
{
conn.Close();
}
}
protected void btn_remove_Click(object sender, EventArgs e)
{
// Get the value from the button ASP.NET gridview
Button btn = (Button)sender;
try
{
conn.Open();
// Make the cart invisible if the id matches with the grid view data source
string query = string.Format("UPDATE tbl_cart SET visible = '{0}' WHERE id = '{1}'", "false", btn.CommandArgument);
command.CommandText = query;
command.ExecuteNonQuery();
Response.Redirect("cart.aspx");
}
finally
{
conn.Close();
}
}
// Multiply all the values of purchases together
public int TotalProductCost()
{
int totalCost = 0;
int currentCost = 0;
int currentQuantity = 0;
for (int i = 0; i < grv_cart.Rows.Count; i++)
{
// Get the data values from the forms
HyperLink hypCost = (HyperLink)grv_cart.Rows[i].Cells[0].FindControl("hyp_productcost");
TextBox txtQuantity = (TextBox)grv_cart.Rows[i].Cells[0].FindControl("txt_productQuantity");
// Sum the product quantity and the product cost
// Attempt to parse your value (removing any non-numeric values)
currentQuantity = Int32.Parse(Regex.Replace(txtQuantity.Text, #"[^\d]", ""));
// Attempt to parse your value (removing any non-numeric values)
currentCost = Int32.Parse(Regex.Replace(hypCost.Text, #"[^\d]", ""));
currentCost *= currentQuantity;
totalCost += currentCost;
}
return totalCost;
}
protected void btn_buy_Click(object sender, EventArgs e)
{
}
protected void btn_update_Click(object sender, EventArgs e)
{
// Get the value from the button ASP.NET gridview
Button btn = (Button)sender;
foreach (GridViewRow grvCart in grv_cart.Rows)
{
Debug.WriteLine(btn.CommandArgument);
TextBox textQuantity = (TextBox)grvCart.FindControl("txt_productQuantity");
int currentQuantity = Int32.Parse(Regex.Replace(textQuantity.Text, #"[^\d]", ""));
try
{
conn.Open();
// Update the cart quantity if the id matches with the grid view data source
string query = string.Format("UPDATE tbl_cart SET product_quantity = '{0}' WHERE id = '{1}'", currentQuantity, btn.CommandArgument);
command.CommandText = query;
command.ExecuteNonQuery();
Response.Redirect("cart.aspx");
}
finally
{
conn.Close();
}
}
}
}
}
Try using the RowCommand event (especially since you already have the CommandArgument set up). That is the more appropriate way to handle this type of action (and that way you can just update one row at a time, without looping through all of them).
Handle the RowCommand event in your GridView declaration:
<asp:GridView ID="grv_cart" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataSourceID="sds_store" ShowHeader="True"
GridLines="None" CssClass="table" OnRowCommand="grv_cart_RowCommand">
And then your event handler would look like this:
protected void grv_cart_RowCommand(Object sender, GridViewCommandEventArgs e)
{
GridViewRow rowToUpdate = grv_cart.Rows[Int.Parse(e.CommandArgument)];
TextBox textQuantity = (TextBox)rowToUpdate.FindControl("txt_productQuantity");
int currentQuantity = Int32.Parse(Regex.Replace(textQuantity.Text, #"[^\d]", ""));
try
{
conn.Open();
// Update the cart quantity if the id matches with the grid view data source
string query = string.Format("UPDATE tbl_cart SET product_quantity = '{0}' WHERE id = '{1}'", currentQuantity, e.CommandArgument);
command.CommandText = query;
command.ExecuteNonQuery();
Response.Redirect("cart.aspx");
}
finally
{
conn.Close();
}
}
Note: You'll want to remove the OnClick handler from the update button:
<asp:Button ID="btn_update" Text="Update" runat="server"
CommandArgument='<%# Eval("id") %>' CssClass="btn btn-warning" />
This is the error I get:
ddlRankEdit' has a SelectedValue which is invalid because it does not
exist in the list of items. Parameter name: value
I have a form wiht several dropdownlists that are nested in a panel that is by default set to invisible. When a user selects a record from a separate list box the selected index changed event sets the panel to visible and makes a data call. That's when the error happens. See the code below, I added XXX where it stalls.
<asp:DropDownList runat="server" ID="ddlRankEdit" CssClass="txtfield" DataSourceID="ODCRanks"
DataTextField="Rank" DataValueField="ID" AppendDataBoundItems="True">
<asp:ListItem Text="--- Select a Rank ---" Value="-1" />
</asp:DropDownList>
<asp:ObjectDataSource ID="ODCRanks" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetRanks"
TypeName="RanksTableAdapters.RankTableAdapter"></asp:ObjectDataSource>
protected void lboxManageMembers_SelectedIndexChanged(object sender, EventArgs e)
{
pnlReviewMemberDetails.Visible = false;
pnlUnlockUserAccount.Visible = false;
pnlAdmins.Visible = false;
pnlCreateAdmins.Visible = false;
lblNote.Visible = false;
pnlManageMenbers.Visible = true;
MembershipUser user = Membership.GetUser();
DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
Guid _memberId = Guid.Empty;
_memberId = new Guid(lbxManageMembers.SelectedValue);
DataSet.MemberInfoDataTable dt = da.GetMember(_memberId);
if (dt.Rows.Count == 1)
{
DataSet.MemberInfoRow mr = dt[0];
XXX ddlRankEdit.SelectedValue = Convert.ToString(mr.rankid);
XXX ddlPatrolEdit.SelectedValue = Convert.ToString(mr.patrolid);
XXX ddlPositionEdit.SelectedValue = Convert.ToString(mr.bsaposid);
txtFirstNameEdit.Text = mr.firstname;
txtLastNameEdit.Text = mr.lastname;
txtEmailEdit.Text = user.Email;
txtAddressEdit.Text = mr.address;
txtPhoneEdit.Text = mr.phone;
txtCellPhoneEdit.Text = mr.altphone;
txtAltEmailEdit.Text = mr.altemail;
txtMotherFirstNameEdit.Text = mr.parentfn;
txtMotherLastNameEdit.Text = mr.parentln;
txtMotherWorkPhoneEdit.Text = mr.parentworkphone;
txtMotheHomePhoneEdit.Text = mr.parentworkphone;
txtMotherCellkPhoneEdit.Text = mr.parentscellphone;
txtMotherTwitterEdit.Text = mr.parenttwitter;
txtMotherEmailEdit.Text = mr.parentemail;
txtMotherAltEmailEdit.Text = mr.parentemailalt;
txtFatherFirstNameEdit.Text = mr.parent2fn;
txtFatherLastNameEdit.Text = mr.parent2ln;
txtFatherWorkPhoneEdit.Text = mr.parent2workphone;
txtFatherHomePhoneEdit.Text = mr.parent2workphone;
txtFatherCellPhoneEdit.Text = mr.parent2cellphone;
txtFatherTwitterEdit.Text = mr.parent2twitter;
txtFatherEmailEdit.Text = mr.parent2email;
txtFatherAltEmailEdit.Text = mr.parent2emailalt;
}
}
The error message is telling you exactly what is happening: the value, for example stored in mr.rankid, is not present in the dropdownlist.
You need to figure out whether or not the dropdownlist contains the correct value or the value you are trying to assign does not exist in the list of available values.
Update
Since it is the visibility of the containing panel that seems to be causing the problems, it would be better to hide the panel using CSS than setting the Visible property to false, which will prevent it from rendering to the page.
This can be done with code similar to the following in the code-behind:
Panel1.Style.Add(HtmlTextWriterStyle.Visibility, "Hidden");
Panel1.Style.Add(HtmlTextWriterStyle.Display, "None");
modify your code like this:
if (dataTable1.Rows[0]["columnName"].ToString() != "" && dataTable1.Rows[0]["columnName"] != null)
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(dataTable1.Rows[0]["columnName"].ToString()));
you can use this codes for use dropdownlist in editemplate when you dont need to use a datasource :
<asp:TemplateField HeaderText="state" SortExpression="state">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList4" runat="server" Style="position: relative" AppendDataBoundItems="true" SelectedValue='<%# Bind("state") %>' >
<asp:ListItem Value="approved">approved</asp:ListItem>
<asp:ListItem Value="notapproved">notapproved</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("state") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>