shopping cart total price issue - asp.net

I am working on a shopping cart project for my college project in final page of my cart i want to calculate the total amount for the all the product in the cart help me in that code for that is
for cart.aspx
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="id"
DataSourceID="SqlDataSource1"
EmptyDataText="No Item in the Cart">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="pName"
HeaderText="pName"
SortExpression="pName" />
<asp:BoundField DataField="brand"
HeaderText="brand"
SortExpression="brand" />
<asp:TemplateField HeaderText="img"
SortExpression="img">
<EditItemTemplate>
<asp:TextBox ID="TextBox1"
runat="server"
Text='<%# Bind("img") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image1"
runat="server"
ImageUrl='<%# Bind("img") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="quantity"
HeaderText="quantity"
SortExpression="quantity" />
<asp:BoundField DataField="price"
HeaderText="price"
SortExpression="price" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1"
runat="server"
ConnectionString="<% $ConnectionStrings:shopingConnectionString1 %>"
DeleteCommand="DELETE FROM [completeCart] WHERE [id] = #id"
InsertCommand="INSERT INTO [completeCart] ([uName], [pName], [brand], [img], [quantity], [price]) VALUES (#uName, #pName, #brand, #img, #quantity, #price)"
SelectCommand="SELECT * FROM [completeCart] WHERE ([uName] = #uName)"
UpdateCommand="UPDATE [completeCart] SET [uName] = #uName, [pName] = #pName, [brand] = #brand, [img] = #img, [quantity] = #quantity, [price] = #price WHERE [id] = #id">
<DeleteParameters>
<asp:Parameter Name="id" Type="Int64" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="uName" Type="String" />
<asp:Parameter Name="pName" Type="String" />
<asp:Parameter Name="brand" Type="String" />
<asp:Parameter Name="img" Type="String" />
<asp:Parameter Name="quantity" Type="Int32" />
<asp:Parameter Name="price" Type="Int64" />
</InsertParameters>
<SelectParameters>
<asp:CookieParameter CookieName="uname"
Name="uName"
Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="uName" Type="String" />
<asp:Parameter Name="pName" Type="String" />
<asp:Parameter Name="brand" Type="String" />
<asp:Parameter Name="img" Type="String" />
<asp:Parameter Name="quantity" Type="Int32" />
<asp:Parameter Name="price" Type="Int64" />
<asp:Parameter Name="id" Type="Int64" />
</UpdateParameters>
</asp:SqlDataSource>
for code behind file
protected void Page_Load(object sender, EventArgs e)
{
string s2 = System.Web.HttpContext.Current.User.Identity.Name;
Response.Cookies["uname"].Value = s2;
}
finally the result i want is the total sum of cost of product display on a label control on the same page

Remove the SqlDataSource control. Don't put SQL in aspx page! Create a class that returns cart and calculates grand total. Databind in code behind.

I am thinking of that your cart.aspx page has a grid view for displaying the cart items and prices , then you can do like this....
you can do like this ... Simply in GridView.RowDataBound Event loop gridview and find control contain price amount and sum them
decimal grdTotal = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
decimal rowTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "price"));
grdTotal = grdTotal + rowTotal;
}
lbl.Text = grdTotal.ToString("c");
}
}
you can display total price value at the footer of price column .......

Related

Conversion from type 'DBNull' to type 'Integer' is not valid. using asp.net and object data source

im try to edit row in gridview called(gvTeam)
the gridview using objectdatasource(odsGvTeam)
in Admin_team.aspx
<asp:GridView ID="gvTeam" runat="server" AutoGenerateColumns="False" DataKeyNames="team_id" DataSourceID="odsGvTeam" AllowPaging="True">
<Columns>
<asp:BoundField DataField="team_id" HeaderText="team_id" InsertVisible="False" ReadOnly="True" SortExpression="team_id" Visible="False" />
<asp:BoundField DataField="team_name" HeaderText="key_team_name" SortExpression="team_name" />
<asp:BoundField DataField="team_lang" HeaderText="key_team_lang" SortExpression="team_lang" />
<asp:BoundField DataField="team_status" HeaderText="key_status" SortExpression="team_status" />
<asp:BoundField DataField="team_key" HeaderText="key_team_key" SortExpression="team_key" />
<asp:BoundField DataField="team_rating" HeaderText="key_team_rating" SortExpression="team_rating" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lnkEditTeam" runat="server" CausesValidation="false" CommandName="edit_team" Text="Edit" CommandArgument='<%# Bind("team_id") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDeleteTeam" runat="server" CausesValidation="false" OnClientClick="return confirm('Are you sure?');" CommandName="delete_team" Text="Delete" CommandArgument='<%# Bind("team_id") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="odsGvTeam" runat="server" DeleteMethod="Delete" InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" SelectMethod="GetData" TypeName="CMS_NG_Sql_V1.dsTeamTableAdapters.taTeam" UpdateMethod="Update">
<DeleteParameters>
<asp:Parameter Name="original_team_id" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="team_name" Type="String" />
<asp:Parameter Name="team_lang" Type="String" />
<asp:Parameter Name="team_status" Type="Int32" />
<asp:Parameter Name="team_key" Type="String" />
<asp:Parameter Name="team_rating" Type="Int32" />
</InsertParameters>
<SelectParameters>
<asp:Parameter DefaultValue="en" Name="team_lang" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="team_name" Type="String" />
<asp:Parameter Name="team_lang" Type="String" />
<asp:Parameter Name="team_status" Type="Int32" />
<asp:Parameter Name="team_key" Type="String" />
<asp:Parameter Name="team_rating" Type="Int32" />
<asp:Parameter Name="team_id" Type="Int32" />
</UpdateParameters>
</asp:ObjectDataSource>
CodeBehing
Protected Sub gvTeam_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles gvTeam.RowCommand
Select Case e.CommandName.ToLower
Case "edit_team"
txtID.Value = e.CommandArgument
Using objTeam As New cls_Team(CInt(txtID.Value))
txtID.Value = objTeam.TeamDataRow.team_id
txtLang.Text = objTeam.TeamDataRow.team_lang
txtRating.Text = objTeam.TeamDataRow.team_rating
txtTeamKey.Text = objTeam.TeamDataRow.team_key
optStatus.SelectedValue = objTeam.TeamDataRow.team_status
txtName.Text = objTeam.TeamDataRow.team_name
MultiView1.SetActiveView(viwEditTeam)
End Using
AdminLogFile(CMS_NG_Sql_V1.enum_AdminLogFile.Edit)
Case "delete_team"
Dim intID As Integer = e.CommandArgument
'Response.Redirect("admin_team.aspx?IDTeam=" & intID)
Using objTeam As New cls_Team(intID)
objTeam.Delete(intID)
AdminLogFile(CMS_NG_Sql_V1.enum_AdminLogFile.Delete)
gvTeam.DataBind()
End Using
End Select
End Sub
the Case "delete_team" work fine
but the Case "edit_team" not worked
i got error:
also i used dataset called (dsTeam.xsd)
how can solved IT ?
A value in the team_rating column is NULL. A database NULL different from a string variable in VB that may have a null value. You need to check for this before assigning a value to txtRating.Text:
If Not objTeam.TeamDataRow.IsNull("team_rating") Then
txtRating.Text = objTeam.TeamDataRow.team_rating
End If

how to read the values of the clicked buttons tow?

I have a grid-view and in one column, I added buttons with every row that it is creating a button. What I need now is, if someone clicks on that button I need to get the field of that corresponding row. I have searched for the solution but i can't find out how to do it ?
*
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:CommandField ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="brandname" HeaderText="brandname" SortExpression="brandname" />
<asp:BoundField DataField="info" HeaderText="info" SortExpression="info" />
<asp:ButtonField DataTextField="brandname" HeaderText="brandname" ButtonType="Button"/>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" DeleteCommand="DELETE FROM [brand_tbl] WHERE [Id] = #original_Id AND (([brandname] = #original_brandname) OR ([brandname] IS NULL AND #original_brandname IS NULL)) AND (([info] = #original_info) OR ([info] IS NULL AND #original_info IS NULL))" InsertCommand="INSERT INTO [brand_tbl] ([brandname], [info]) VALUES (#brandname, #info)" OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT * FROM [brand_tbl]" UpdateCommand="UPDATE [brand_tbl] SET [brandname] = #brandname, [info] = #info WHERE [Id] = #original_Id AND (([brandname] = #original_brandname) OR ([brandname] IS NULL AND #original_brandname IS NULL)) AND (([info] = #original_info) OR ([info] IS NULL AND #original_info IS NULL))">
<DeleteParameters>
<asp:Parameter Name="original_Id" Type="Int32" />
<asp:Parameter Name="original_brandname" Type="String" />
<asp:Parameter Name="original_info" Type="String" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="brandname" Type="String" />
<asp:Parameter Name="info" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="brandname" Type="String" />
<asp:Parameter Name="info" Type="String" />
<asp:Parameter Name="original_Id" Type="Int32" />
<asp:Parameter Name="original_brandname" Type="String" />
<asp:Parameter Name="original_info" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
*
protected void gView_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView rowView= (DataRowView)e.Row.DataItem;
if (rowView["ColumnId"] != DBNull.Value)
{
var val =rowView["ColumnId"];
}
}
// you can also do like this
void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
//Check if it's the right CommandName...
if(e.CommandName=="Add")
{
// do code
}
}
you can define DataKeyNames on GridView, follow this:
DataKeyNames in GridView

DetailsView in Modalpopup won't load on second click on edit button

I have a GridView that when you click the edit button it loads a DetailsView in Edit Mode inside of a ModalPopup. It works fine the first time you click edit. If you click edit again to make changes to a second record, it loads but the DetailsView is not in the ModalPopup.
Can anyone tell me what I"m doing wrong? My code is below.
GridView datasource:
<asp:SqlDataSource ID="sdsMembers" runat="server"
ConnectionString="<%$ ConnectionStrings:DoseRec_ABTConnectionString %>"
SelectCommand="SELECT [intMemberID], [vcharTitle], [vcharFirstName], [vcharLastName], [vcharSuffix], [vcharJobTitle], [vcharAddress1], [vcharAddress2], [vcharCity], [vcharState], [vcharZipCode], [vcharPhone], [vcharFax], [bitActive] FROM [tbl_Members]"
DeleteCommand="DELETE FROM [tbl_Members] WHERE [intMemberID] = #intMemberID"
InsertCommand="INSERT INTO [tbl_Members] ([vcharTitle], [vcharFirstName], [vcharLastName], [vcharSuffix], [vcharJobTitle], [vcharAddress1], [vcharAddress2], [vcharCity], [vcharState], [vcharZipCode], [vcharPhone], [vcharFax], [bitActive]) VALUES (#vcharTitle, #vcharFirstName, #vcharLastName, #vcharSuffix, #vcharJobTitle, #vcharAddress1, #vcharAddress2, #vcharCity, #vcharState, #vcharZipCode, #vcharPhone, #vcharFax, #bitActive)"
UpdateCommand="UPDATE [tbl_Members] SET [vcharTitle] = #vcharTitle, [vcharFirstName] = #vcharFirstName, [vcharLastName] = #vcharLastName, [vcharSuffix] = #vcharSuffix, [vcharJobTitle] = #vcharJobTitle, [vcharAddress1] = #vcharAddress1, [vcharAddress2] = #vcharAddress2, [vcharCity] = #vcharCity, [vcharState] = #vcharState, [vcharZipCode] = #vcharZipCode, [vcharPhone] = #vcharPhone, [vcharFax] = #vcharFax, [bitActive] = #bitActive WHERE [intMemberID] = #intMemberID">
<DeleteParameters>
<asp:Parameter Name="intMemberID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="vcharTitle" Type="String" />
<asp:Parameter Name="vcharFirstName" Type="String" />
<asp:Parameter Name="vcharLastName" Type="String" />
<asp:Parameter Name="vcharSuffix" Type="String" />
<asp:Parameter Name="vcharJobTitle" Type="String" />
<asp:Parameter Name="vcharAddress1" Type="String" />
<asp:Parameter Name="vcharAddress2" Type="String" />
<asp:Parameter Name="vcharCity" Type="String" />
<asp:Parameter Name="vcharState" Type="String" />
<asp:Parameter Name="vcharZipCode" Type="String" />
<asp:Parameter Name="vcharPhone" Type="String" />
<asp:Parameter Name="vcharFax" Type="String" />
<asp:Parameter Name="bitActive" Type="Boolean" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="vcharTitle" Type="String" />
<asp:Parameter Name="vcharFirstName" Type="String" />
<asp:Parameter Name="vcharLastName" Type="String" />
<asp:Parameter Name="vcharSuffix" Type="String" />
<asp:Parameter Name="vcharJobTitle" Type="String" />
<asp:Parameter Name="vcharAddress1" Type="String" />
<asp:Parameter Name="vcharAddress2" Type="String" />
<asp:Parameter Name="vcharCity" Type="String" />
<asp:Parameter Name="vcharState" Type="String" />
<asp:Parameter Name="vcharZipCode" Type="String" />
<asp:Parameter Name="vcharPhone" Type="String" />
<asp:Parameter Name="vcharFax" Type="String" />
<asp:Parameter Name="bitActive" Type="Boolean" />
<asp:Parameter Name="intMemberID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
DetailsView datasource:
<asp:SqlDataSource ID="sdsMembersDetail" runat="server"
ConnectionString="<%$ ConnectionStrings:DoseRec_ABTConnectionString %>"
SelectCommand="SELECT [intMemberID] AS ID, [vcharTitle] AS Title, [vcharFirstName] AS 'First Name', [vcharLastName] AS 'Last Name', [vcharSuffix] AS Suffix, [vcharJobTitle] AS 'Job Title', [vcharAddress1] AS Address1, [vcharAddress2] AS Address2, [vcharCity] AS City, [vcharState] AS State, [vcharZipCode] AS 'Zip Code', [vcharPhone] AS Phone, [vcharFax] AS Fax, [bitActive] AS Active FROM [tbl_Members] WHERE ([intMemberID] = #intMemberID)">
<SelectParameters>
<asp:QueryStringParameter DefaultValue="" Name="intMemberID"
QueryStringField="intMemberID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
GridView markup:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvMembers" runat="server" AutoGenerateColumns="False"
DataKeyNames="intMemberID" DataSourceID="sdsMembers" style="background-color:White;">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:TemplateField ControlStyle-Width="50px" HeaderStyle-Width="60px">
<ItemTemplate>
<asp:LinkButton ID="btnViewDetails" runat="server" OnClick="BtnViewDetails_Click">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="intMemberID" HeaderText="ID"
InsertVisible="False" ReadOnly="True" SortExpression="intMemberID" />
<asp:BoundField DataField="vcharTitle" HeaderText="vcharTitle"
SortExpression="vcharTitle" />
<asp:BoundField DataField="vcharFirstName" HeaderText="First Name"
SortExpression="vcharFirstName" />
<asp:BoundField DataField="vcharLastName" HeaderText="Last Name"
SortExpression="vcharLastName" />
<asp:BoundField DataField="vcharSuffix" HeaderText="Suffix"
SortExpression="vcharSuffix" />
<asp:BoundField DataField="vcharJobTitle" HeaderText="Job Title"
SortExpression="vcharJobTitle" />
<asp:BoundField DataField="vcharAddress1" HeaderText="Address1"
SortExpression="vcharAddress1" />
<asp:BoundField DataField="vcharAddress2" HeaderText="Address2"
SortExpression="vcharAddress2" />
<asp:BoundField DataField="vcharCity" HeaderText="City"
SortExpression="vcharCity" />
<asp:BoundField DataField="vcharState" HeaderText="State"
SortExpression="vcharState" />
<asp:BoundField DataField="vcharZipCode" HeaderText="Zip Code"
SortExpression="vcharZipCode" />
<asp:BoundField DataField="vcharPhone" HeaderText="Phone"
SortExpression="vcharPhone" />
<asp:BoundField DataField="vcharFax" HeaderText="Fax"
SortExpression="vcharFax" />
<asp:CheckBoxField DataField="bitActive" HeaderText="Active"
SortExpression="bitActive" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
DetailsView marup:
<asp:Button id="btnShowPopup" runat="server" style="display:none" />
<ajaxToolKit:ModalPopupExtender
ID="mdlPopup" runat="server" TargetControlID="btnShowPopup" PopupControlID="pnlPopup"
CancelControlID="btnClose" BackgroundCssClass="modalBackground" />
<asp:Panel ID="pnlPopup" runat="server" Width="500px" style="display:none">
<asp:UpdatePanel ID="updPnlCustomerDetail" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblMemberDetail" runat="server" Text="Member Detail" BackColor="lightblue" Width="95%" />
<asp:DetailsView ID="dvMemberDetail" runat="server" DefaultMode="Edit" Width="95%" BackColor="white" OnItemUpdating="dvMembersDetail_ItemUpdating">
</asp:DetailsView>
</ContentTemplate>
</asp:UpdatePanel>
<div align="right" style="width:95%">
<asp:LinkButton
ID="btnSave" runat="server" Text="Save"
Width="50px" onclick="btnSave_Click" />
<asp:LinkButton ID="btnClose" runat="server">Close</asp:LinkButton>
</div>
</asp:Panel>
Click event (to display the DetailsView):
protected void BtnViewDetails_Click(object sender, EventArgs e)
{
LinkButton btnDetails = sender as LinkButton;
GridViewRow row = (GridViewRow)btnDetails.NamingContainer;
this.sdsMembersDetail.SelectParameters.Clear();
this.sdsMembersDetail.SelectParameters.Add("intMemberID", Convert.ToString(this.gvMembers.DataKeys[row.RowIndex].Value));
this.dvMemberDetail.DataSource = this.sdsMembersDetail;
this.dvMemberDetail.DataBind();
this.updPnlCustomerDetail.Update();
this.mdlPopup.Show();
}
If any other code, like the code for my save button is needed just let me know and I will post it.
Here's my Save code:
protected void btnSave_Click(object sender, EventArgs e)
{
if (this.Page.IsValid)
{
this.dvMemberDetail.UpdateItem(true);
this.dvMemberDetail.ChangeMode(DetailsViewMode.ReadOnly);
this.dvMemberDetail.Visible = false;
this.mdlPopup.Hide();
this.gvMembers.DataBind();
this.UpdatePanel1.Update();
}
}
protected void dvMembersDetail_ItemUpdating(object sender, EventArgs e)
{
using (DoseRec_ABTEntities1 dbContext = new DoseRec_ABTEntities1())
{
TextBox id = (TextBox)dvMemberDetail.Rows[0].Cells[1].Controls[0];
int intID = Convert.ToInt32(id.Text);
tbl_Members mem = (from m in dbContext.tbl_Members
where m.intMemberID == intID
select m).Single();
TextBox title = (TextBox)dvMemberDetail.Rows[1].Cells[1].Controls[0];
TextBox firstname = (TextBox)dvMemberDetail.Rows[2].Cells[1].Controls[0];
TextBox lastname = (TextBox)dvMemberDetail.Rows[3].Cells[1].Controls[0];
TextBox suffix = (TextBox)dvMemberDetail.Rows[4].Cells[1].Controls[0];
TextBox jobtitle = (TextBox)dvMemberDetail.Rows[5].Cells[1].Controls[0];
TextBox address1 = (TextBox)dvMemberDetail.Rows[6].Cells[1].Controls[0];
TextBox address2 = (TextBox)dvMemberDetail.Rows[7].Cells[1].Controls[0];
TextBox city = (TextBox)dvMemberDetail.Rows[8].Cells[1].Controls[0];
TextBox state = (TextBox)dvMemberDetail.Rows[9].Cells[1].Controls[0];
TextBox zipcode = (TextBox)dvMemberDetail.Rows[10].Cells[1].Controls[0];
TextBox phone = (TextBox)dvMemberDetail.Rows[11].Cells[1].Controls[0];
TextBox fax = (TextBox)dvMemberDetail.Rows[12].Cells[1].Controls[0];
CheckBox active = (CheckBox)dvMemberDetail.Rows[13].Cells[1].Controls[0];
mem.vcharTitle = title.Text;
mem.vcharFirstName = firstname.Text;
mem.vcharLastName = lastname.Text;
mem.vcharSuffix = suffix.Text;
mem.vcharJobTitle = jobtitle.Text;
mem.vcharAddress1 = address1.Text;
mem.vcharAddress2 = address2.Text;
mem.vcharCity = city.Text;
mem.vcharState = state.Text;
mem.vcharZipCode = zipcode.Text;
mem.vcharPhone = phone.Text;
mem.vcharFax = fax.Text;
mem.bitActive = active.Checked;
dbContext.SaveChanges();
}
}

Deleting row from Repeater

I have the following Repeater on my page:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1"
onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<div id="fullcommentheader">
<span class="fullname">
<asp:Literal ID="Literal3" runat="server" Text='<%# Eval("Name") %>'></asp:Literal></span>
<br />
<span class="fullbodytext">
<asp:Button ID="Button2" runat="server" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' Text="Delete" />
<asp:Literal ID="LitBody2" Text='<%# Eval("Message")%>' runat="server"></asp:Literal></span>
<span class="dateTime">
<asp:Literal ID="Literal4" runat="server" Text='<%# Eval("CreateDateTime") %>'></asp:Literal></span>
</div>
<br />
</ItemTemplate>
</asp:Repeater>
I have a Button2 there that I'd like to use to delete the repeater entry, how do I query the database to achieve this? I'm used to have these commands by default on gridview, so I'm unsure on how to do this manually.
My event:
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Delete" && e.CommandArgument.ToString() != "")
{
}
}
This is my SqlDataSource:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:orangefreshConnectionString1 %>"
DeleteCommand="DELETE FROM [Comment] WHERE [Id] = #Id"
InsertCommand="INSERT INTO [Comment] ([Name], [Email], [Website], [Message], [PostId]) VALUES (#Name, #Email, #Website, #Message, #PostId)"
SelectCommand="SELECT [Name], [Email], [Website], [Message], [PostId], [Id], [CreateDateTime] FROM [Comment] WHERE ([PostId] = #PostId)"
UpdateCommand="UPDATE [Comment] SET [Name] = #Name, [Email] = #Email, [Website] = #Website, [Message] = #Message, [PostId] = #PostId, [CreateDateTime] = #CreateDateTime WHERE [Id] = #Id">
<DeleteParameters>
<asp:Parameter Name="Id" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Name" Type="String" />
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="Website" Type="String" />
<asp:Parameter Name="Message" Type="String" />
<asp:QueryStringParameter Name="PostId" QueryStringField="Id" Type="Int32" />
<asp:Parameter Name="CreateDateTime" Type="DateTime" />
</InsertParameters>
<SelectParameters>
<asp:QueryStringParameter Name="PostId" QueryStringField="Id" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Name" Type="String" />
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="Website" Type="String" />
<asp:Parameter Name="Message" Type="String" />
<asp:Parameter Name="PostId" Type="Int32" />
<asp:Parameter Name="CreateDateTime" Type="DateTime" />
<asp:Parameter Name="Id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
You will need to declare a private int _id global variable first.
Then, add the parameter dynamically in your sqldatasource deleting event:
Then in your ItemCommand 'delete', set the global _id to the CommandArgument since you passed that in. Then perform a SqlDataSource1.Delete()
_id = Convert.ToInt32(e.CommandArgument);
SqlDataSource1.Delete();
_id = 0;
//need to rebind your repeater here or you won't see the changes
protected void SqlDataSource1_Deleting(object sender, SqlDataSourceCommandEventArgs e)
{
//add the parameter
if (_id != 0)
e.Command.Parameters["#Id"].Value = _id;
}
Use the ItemCommand event for the repeater. This will trigger when the button is clicked and give you access to the command name and command argument. You can then use the command argument to delete the record from the database.
Do delete the record, you can use the SqlDataSource.Delete() method, but you will need to populate the delete parameter before calling that method or handle the Deleting event and populate the parameters there.

SqlDataSource Insert code behind variable

I have the following SqlDataSource
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:orangefreshConnectionString1 %>"
InsertCommand="INSERT INTO [Chat] ([Username], [Message]) VALUES (#Username, #Message)"
SelectCommand="SELECT [Id], [Username], [Message], [Date] FROM [Chat] ORDER BY [Id]" >
<InsertParameters>
<asp:Parameter Name="Message" Type="String" />
<asp:Parameter Name="Date" Type="DateTime" />
<asp:Parameter Name="Username" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
Which controls the following FormView:
<asp:FormView ID="FormView1" runat="server" DefaultMode="Insert"
OnItemInserted="fv_ItemInserted" RenderOuterTable="False"
DataSourceID="SqlDataSource1">
<InsertItemTemplate>
<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
<asp:TextBox ID="TextBox1" runat="server" CssClass="chattxtbox"
Text='<%# Bind("Message") %>' autocomplete="off"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CommandName="insert" style="display:none" Text="Button" OnClick="insertUser"/>
</asp:Panel>
</InsertItemTemplate>
</asp:FormView>
I want to be able a variable's content into the Username column, so on Button1 I set the following event: OnClick="insertUser"
protected void insertUser(object sender, EventArgs e)
{
string username1 = User.Identity.Name;
SqlDataSource1.InsertParameters.Add("Username", username1);
SqlDataSource1.Insert();
}
This isn't working though, I don't get any SQL error message at all, is this the right way to do this? And where did I go wrong?
Change Insert Parameter to SessionParameter.
<InsertParameters>
<asp:Parameter Name="Message" Type="String" />
<asp:Parameter Name="Date" Type="DateTime" />
<asp:Parameter Name="Username" Type="String" />
<asp:SessionParameter Name="Username" SessionField="Username" Type="String" />
</InsertParameters>
And in Page_Load handler,
Session["Username"]=User.Identity.Name;
Here you want to declare your parameter as a Control Parameter and then you don't need to assign the value to the parameter in code. You can just call insert.

Resources