I have placed a checkboxlist in a formview object.
I would like to store and load the results of the checkboxlist in a table of an entity framework.
I filled the cbl with values and labels coming from a table that has 2 columns, using the DataSourceID, DataTextField and DataValueField attributes but I can't seem to find how to bind the cbl to the entity framework object in order to store the checked values when the formview is in "EDIT" mode.
Any help would be appreciate. Thanks!
<asp:FormView ID="formView1" runat="server" DataSourceID="Ods1"
Height="203px" Width="495px"
onpageindexchanging="formView1_PageIndexChanging">
<EditItemTemplate>
<asp:CheckBoxList ID="cblProducts" runat="server" RepeatColumns="3"
Width="782px" DataSourceID="SqlDataSource1" DataTextField="ProductName"
DataValueField="ProductCode">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [ProductCode], [ProductName] FROM [Products]">
</asp:SqlDataSource>
</EditItemTemplate>
</asp:FormView>
<asp:ObjectDataSource ID="Ods1" runat="server"
DataObjectTypeName="WebApplication1.EDM.Emp" DeleteMethod="DeleteEmp"
InsertMethod="CreateNewEmp" OldValuesParameterFormatString="original_{0}"
SelectMethod="GetEmpByEmpId" TypeName="WebApplication1.EDM.EmpLogic"
UpdateMethod="UpdateEmp" OnSelecting="Ods1_Selecting">
<SelectParameters>
<asp:RouteParameter Name="EmpId" RouteKey="EmpId" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:FormView ID="formView1" runat="server"
OnItemUpdating="formView1_ItemUpdating" ...>
protected void formView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
var cblProducts = formView1.FindControl("cblProducts") as CheckBoxList;
foreach (ListItem item in cblProducts.Items)
{
if (item.Selected)
{
// Check if item.Value is not in the db for this employee, if so add it
}
else
{
// Check if item.Value is in the db for this employee, if so delete it
}
}
// save
}
You need to do the following;
foreach (ListItem chk in cblProducts.Items)
{
string productId= chk.Value;
if (IsProductAvailable(productId) // this method will basically goes to database and return true of false
chk.Selected = true;
else
chk.Selected = false;
}
private void IsProductAvailable(string productId)
{
string query = "SELECT [ProductId] FROM [Product] ";
query += "WHERE [ProductId] = #ProductId";
DbCommand comm = new DbCommand();
comm.CommandText = query;
DbParameter param = comm.CreateParameter();
param.ParameterName = "#ProductId";
param.Value = productId;
comm.Parameters.Add(param);
DataTable table = comm.ExecuteCommand();
if (table.Rows.Count > 0)
{
return true;
}
else
return false;
}
please modify query and parameters according to your need.
Related
I have two SqlDataSources that relate to two dropdownlists. The PopulateDLL() method allows me to populate the first dropdownlist with towns and filters the second dropdownlist with street names related to that town, however some street names also have building names (i.e. City Hall, Main Street), what I'm trying to do is include the building name with the appropriate street names. I researched this and got the code
dt.Columns.Add("StreetName + BuildingName");
ddl_FilteredLocation.DataTextField = "BuildingName";
//ddl_FilteredLocation.DataValueField = "";
ddl_FilteredLocation.DataBind();
However it still only calls the street name, I've tried different variations and sometimes only the building name will appear but no street name, any help with this would be great, thanks!
<%-- DS for DDL Location --%>
<asp:SqlDataSource ID="ds_Location" EnableCaching="false" DataSourceMode="DataSet" runat="server" >
ConnectionString="<%$ ConnectionStrings:DataTown %>"
SelectCommand="SELECT DISTINCT Town FROM [DataTown].[dbo].[DT] Order By Town">
<asp:SqlDataSource>
<%-- DS for DDL Street Name, filterExpression is used so that when a user selects a town from ddl_Location the streets for that town are filtered --%>
<asp:SqlDataSource ID="ds_StreetName" EnableCaching="true" DataSourceMode="DataSet" runat="server" ConnectionString="<%$ ConnectionStrings:DataTown %>"
SelectCommand="SELECT Town, BuildingName, StreetName FROM [DataTown].[dbo].[DT] Order By StreetName" FilterExpression="Town = '{0}'">
<FilterParameters>
<asp:ControlParameter Name="Town" ControlID="fmv_AccidentHSUData$ddl_Location" PropertyName="SelectedValue" />
</FilterParameters>
</asp:SqlDataSource>
<asp:DropDownList ID="ddl_Location" AutoPostBack="true" Width="100%" runat="server"></asp:DropDownList>
<asp:DropDownList ID="ddl_FilteredLocation" DataSourceID="ds_StreetName" DataTextField="StreetName" DataValueField="StreetName" AutoPostBack="true" Width="100%" runat="server">
protected void PopulateDDL()
{
DropDownList ddl_Location = (DropDownList)fmv_DataTown.FindControl("ddl_Location");
DropDownList ddl_FilteredLocation = (DropDownList)fmv_DataTown.FindControl("ddl_FilteredLocation");
ddl_Location.Items.Clear();
DataView view = (DataView)ds_Location.Select(DataSourceSelectArguments.Empty);
DataTable dt = view.ToTable();
dt.Columns.Add("StreetName + BuildingName");
ddl_FilteredLocation.DataTextField = "BuildingName";
//ddl_FilteredLocation.DataValueField = "";
ddl_FilteredLocation.DataBind();
foreach (DataRow row in dt.Rows)
{
string Town = row["Town"].ToString();
//string StreetName = row["StreetName"].ToString();
string FullText = "";
if (Town.Length > 0)
{
FullText = Town;
}
else
{
}
ddl_Location.Items.Add(new ListItem(FullText, FullText));
}
}
The code underneath is the solution to the problem I had
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
PopulateDDL();
}
}
protected void PopulateDDL()
{
DropDownList ddl_Location = (DropDownList)fmv_DataTown.FindControl("ddl_Location");
DropDownList ddl_FilteredLocation = (DropDownList)fmv_DataTown.FindControl("ddl_FilteredLocation");
ddl_Location.Items.Clear();
DataView view = (DataView)ds_Location.Select(DataSourceSelectArguments.Empty);
DataTable dt = view.ToTable();
foreach (DataRow row in dt.Rows)
{
string Town = row["Town"].ToString();
string FullText = "";
if (Town.Length > 0)
{
FullText = Town;
}
else
{
}
ddl_Location.Items.Add(new ListItem(FullText, FullText));
}
}
Inside gridview a dropdownlist is there
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:DropDownList ID="quantity" runat="server" DataValueField="ItemID" DataTextField="Quantity">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
for each itemid there is some numeric value in Quantity field of Database Table
i want that this dropdown must contain the values from 1 to quantity.DataTextField for all the items present in the cart
the procedure by which gridview is bound is
create proc [dbo].[prcItemsinCart](#CartID int)
as
select distinct ct.Price,ct.Quantity,ct.ItemID,
ct.CartID,ct.ProductID,p.ProductName,
isnull(( select top 1 convert(varchar,PhotoID,10) + '.' + ExtName
from ProductPhoto
where ProductID = ct.ProductID ),'NoImage.jpg'
) as Product,
( Select Price*Quantity
from CartItems
where CartID=ct.CartID and ProductID=ct.ProductID
) as SubTotal
from CartItems as ct
inner join ProductInfo as p on ct.ProductID=p.ProductID
inner join ProductPhoto as pp on ct.ProductID=pp.ProductID
where ct.CartID=#CartID
I would add a HiddenField in the TemplateField to hold the CartID, I will use the CartID in the code. My Markup should look like:
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:HiddenField ID="hdnId" runat="server" value='<%#Eval("CartID") %>'></asp:HiddenField>
<asp:DropDownList ID="quantity" runat="server" DataValueField="ItemID" DataTextField="Quantity">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
In the code, in GridView's RowDataBound I am finding the DropDownList and HiddenField, running a Sql Query to bring my expected data, and binding them to my DropdownList:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList quantity = e.Row.FindControl("quantity") as DropDownList;
HiddenField hdnId = e.Row.FindControl("hdnId") as HiddenField;
if (quantity != null && hdnId != null)
{
string queryString = String.Format("SELECT ItemID, Quantity FROM CartItems WHERE CartID= {0}", hdnId.Value);
//MyConnectionString is your connection string in web.config
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString()))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
quantity.DataSource = reader;
quantity.DataValueField = "ItemID";
quantity.DataTextField = "Quantity";
quantity.DataBind();
}
}
}
}
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" />
i have an application where a user logs in and can edit his/other's data. however, if the user is an admin, he gets a gridview with all user's records which he can edit. if the user is not an admin, he will just get a listview where he can edit his own data.
when a user logs into the page, his userid, which is in itself also stored in the db, is stored as a session variable in Session["ID"]. now i need to populate the listview with the user's data. i thought it would be good to just query the data based on the Session["ID"] parameter. but i am not sure how to do this.
EDIT:
ok i have little code regarding this as i have no idea how to do it but i will post what i have. first is the method where i set the session variable of the userid:
objda = new SqlDataAdapter("[GetIDOfUser]", objcon);
objda.SelectCommand.CommandType = CommandType.StoredProcedure;
objda.SelectCommand.Parameters.Add("#Username", SqlDbType.VarChar).Value = tbUsername.Text;
objda.SelectCommand.Parameters.Add("#UserPassword", SqlDbType.VarChar).Value = tbPassword.Text;
String id = (string)objda.SelectCommand.ExecuteScalar();
Session["ID"] = id;
this is my markup:
<asp:ListView ID="ListView1" Visible="False" runat="server" DataSourceID="SqlDataSource2"></asp:ListView>
this is the code where i enable the listview:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserAuthentication"] == null)
{
Response.Redirect("Login.aspx");
}
if (Session["Benutzerart"].ToString() == Enums.Enumerations.Benutzer.Administrator.ToString())
{
GridView1.Visible = true;
//Set controls for admin
}
if (Session["Benutzerart"].ToString() != Enums.Enumerations.Benutzer.Administrator.ToString())
{
ListView1.Visible = true;
//Set controls for other users
}
}
ok guys i have figured it out:
i just make normal listview as in the code above. only the data source has no selectcommand attribute in the markup. this attribute is set in-code:
if (Session["Benutzerart"].ToString() != Enums.Enumerations.Benutzer.Administrator.ToString())
{
ListView1.Visible = true;
SqlDataSource2.SelectCommand = "SELECT [Titel], [Bezeichnung], [Vorname], [Nachname], [Geburtsdatum], [Geburtsort], [Straße], [Nationalität], [Hausnummer], [PLZ], [Ort], [Land], [Mobil], [UrlaubstageGenommen], [UrlaubstageInsgesamt], [Status], [Benutzerart], [Homepage], [Email], [Festnetz], [Fax], [UrlaubstageRest], [Username], [UserPassword] FROM [Benutzer] WHERE [BenutzerID] = '" + Session["ID"] + "'";
}
markup of datasource:
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ></asp:SqlDataSource>
you are binding listview with SqlDataSource, use sqldatasource SelectParameter
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:yourConnection %>"
SelectCommand="SELECT * FROM yourTable WHERE userid = #userid">
<SelectParameters>
<asp:SessionParameter Name="userid" SessionField="ID" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
To select data from DB you can create sql data source and bind it to ListView:
SqlDataSource ds = new SqlDataSource();
ds.ConnectionString = yourDBconnectionString;
ds.SelectCommand = "SELECT * FROM records_table WHERE user_id=#user_id";
ds.SelectParameters.Add("user_id", Convert.ToInt32(Session["id"]));
ListView1.DataSource = ds;
ListView1.DataBind();
Then to bind records fields to ListView on aspx page use (just an example):
<%# Eval("recort_title") %>
When I select a value from the dropdownlist, I like that value to be save in the #TimeZone value that is needed for
InsertCommand="INSERT INTO [Companies] ([TimeZone]) VALUES ( #TimeZone)"
I am not sure how to do this.
Here is my code:
Within my page load, I have the following code that assigns value to the drop down:
ddlTimeZone.DataSource = from p in TimeZoneInfo.GetZones()
select new { p.Id };
ddlTimeZone.DataTextField = "Id";
ddlTimeZone.DataValueField = "Id";
ddlTimeZone.DataBind();
Next, within my .aspx file, I have the following:
<EditItemTemplate>
<asp:DropDownList ID="ddlTimeZone" runat="server">
</asp:DropDownList>
</EditItemTemplate>
..... .....
InsertCommand="INSERT INTO [Companies] ([TimeZone]) VALUES ( #TimeZone)"
<InsertParameters>
<asp:Parameter Name="TimeZone" Type="String" />
</InsertParameters>
Again, what I need to know is how to I bind the selected value from the dropdownlist (ddlTimeZone) to #TimeZone
I tried:
<asp:DropDownList ID="ddlTimeZone" SelectedValue='<%# Bind("TimeZone") %>' runat="server">
</asp:DropDownList>
But that did not work. NOTE THAT I AM USING THE DROPDOWNLIST WITHIN A GRIDVIEW.
Try this way
var command = new SqlCommand("INSERT INTO [Companies] ([TimeZone]) VALUES ( #TimeZone)", connection);
command.Parameters.Add(new SqlParameter("#TimeZone", valuetopass));