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.
Related
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
We have a DropDownList in the markup of an ASP.Net / VB.Net web form.
We are wanting to populate the DropDownList with data from a DataSet created from the DataSet designer but the coding we are using in the code-behind file does not find the DropDownList ID using FindControl.
Can you check my coding and let me know what I still need to do to get the DropDownList populated?
Markup of the DropDownList:
<% '-- DetailsView (Grid) for details of the GridView -- %>
<% '---------------------------------------------------- %>
<asp:DetailsView
ID="DetailsView"
runat="server"
AutoGenerateRows="False"
Height="50px"
Width="207px"
DataSourceID="SqlDataSourceDetails"
DataKeyNames="ID"
OnItemCommand="DetailsViewDetails_ItemCommand"
OnDataBound="DetailsView_DataBound">
<Fields>
<asp:TemplateField HeaderText="Class:" SortExpression="ClassID">
<EditItemTemplate>
<asp:DropDownList ID="DropDownListClass" Runat="server"> </asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorEditDropDownListClass" runat="server"
ControlToValidate="DropDownListClass"
ErrorMessage="Please select a class." Font-Bold="True" Font-Italic="True" ForeColor="Red"
SetFocusOnError="True" Display="Dynamic">
</asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Literal ID="LiteralClass" runat="server"
Text='<%# FormatAsMixedCase(Eval("ClassName").ToString())%>' />
</ItemTemplate>
<ItemStyle ForeColor="Blue" />
</asp:TemplateField>
</Fields>
Coding in the code-behind file:
Protected Sub DetailsView_DataBound(sender As Object, e As EventArgs)
Dim theClassesTableAdapter As New DataSetClassesTableAdapters.ClassesTableAdapter
Dim ddlTheDropDownList = DirectCast(FindControl("DropDownListClass"), DropDownList)
ddlTheDropDownList.DataSource = theClassesTableAdapter.GetDataByAllClasses
ddlTheDropDownList.DataTextField = "ClassName"
ddlTheDropDownList.DataValueField = "ClassID"
ddlTheDropDownList.SelectedValue = "ClassID"
ddlTheDropDownList.DataBind()
End Sub
Markup of the DataSouce of the DetailsView:
<% '-- Datasources -- %>
<% '----------------- %>
<asp:SqlDataSource
ID="SqlDataSourceDetails"
runat="server"
ConnectionString="<%$ ConnectionStrings:Knowledge Academy %>"
DeleteCommand=
"DELETE FROM [TeacherSchedule]
WHERE [ID] = #ID"
InsertCommand=
"INSERT INTO [TeacherSchedule]
([DayOfWeek],
[Grade],
[StartTime],
[EndTime],
[ClassID])
VALUES (#DayOfWeek,
#Grade,
#StartTime,
#EndTime,
#ClassID)"
SelectCommand=
"SELECT TeacherSchedule.ID, TeacherSchedule.Grade, TeacherSchedule.StartTime, TeacherSchedule.EndTime, TeacherSchedule.TeacherID, TeacherSchedule.ClassID,
TeacherSchedule.DayOfWeek, Classes.ClassName, Teachers.Forename, Teachers.Surname
FROM TeacherSchedule INNER JOIN
Classes ON TeacherSchedule.ID = Classes.ID INNER JOIN
Teachers ON TeacherSchedule.ID = Teachers.ID
WHERE (TeacherSchedule.ID = #ID)"
UpdateCommand=
"UPDATE [TeacherSchedule]
SET [DayOfWeek] = #DayOfWeek,
[Grade] = #Grade,
[StartTime] = #StartTime,
[EndTime] = #EndTime,
[ClassID] = #ClassID
WHERE [ID] = #ID">
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="DayOfWeek" Type="String" />
<asp:Parameter Name="Grade" Type="String" />
<asp:Parameter Name="StartTime" Type="String" />
<asp:Parameter Name="EndTime" Type="String" />
<asp:Parameter Name="ClassID" Type="Int32" />
</InsertParameters>
<SelectParameters>
<asp:ControlParameter ControlID="GridViewSummary" Name="ID" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="DayOfWeek" Type="String" />
<asp:Parameter Name="Grade" Type="String" />
<asp:Parameter Name="StartTime" Type="String" />
<asp:Parameter Name="EndTime" Type="String" />
<asp:Parameter Name="ClassID" Type="Int32" />
<asp:Parameter Name="ID" />
</UpdateParameters>
</asp:SqlDataSource>
Try and populate your DropDownList in the DropDownList_Init event handler.
Markup:
<asp:DropDownList ID="ddlTheDropDownList" runat="server" OnInit="ddlTheDropDownList_Init">
The code behind should look something like this, I'm more used to C# but I hope you understand the point:
Protected Sub ddlTheDropDownList_Init(sender As Object, e As EventArgs)
Dim ddl As DropDownList
ddl = sender As DropDownList
ddl.Datasource = theClassesTableAdapter.GetDataByAllClasses
ddl.DataTextField = "ClassName"
ddl.DataValueField = "ClassID"
ddl.SelectedValue = "ClassID"
ddl.DataBind()
End Sub
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.
i am trying to bind an sqldatasource from the code by passing variable from another page, but when i run the report i am getting 0 records,
, my code as fllow
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:WorkflowConnStr %>"
SelectCommand="SELECT * FROM tbl_ServiceTracking WHERE (ActorUID = #strUserId) AND (RequestedDate >= #DateFrom) AND (RequestedDate <= #DateTo)">
<SelectParameters>
<asp:Parameter Name="strUserId" />
<asp:Parameter Name="DateFrom" />
<asp:Parameter Name="DateTo" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" />
c# code
string strUserId = Request.QueryString["userid"];
string DateFrom = Request.QueryString["dtfrom"];
string DateTo = Request.QueryString["dtto"];
SqlDataSource1.SelectParameters.Add("strUserId", strUserId);
SqlDataSource1.SelectParameters.Add("DateFrom", DateFrom);
SqlDataSource1.SelectParameters.Add("DateTo", DateTo);
SqlDataSource1.DataSourceMode = SqlDataSourceMode.DataReader;
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
did i miss something?
I solved this problem by changing my code
SqlDataSource1.SelectParameters["strUserId"].DefaultValue = strUserId;
SqlDataSource1.SelectParameters["DateFrom"].DefaultValue = DateFrom;
SqlDataSource1.SelectParameters["DateTo"].DefaultValue = DateTo;
You can also set select parameter in design mode:
<SelectParameters>
<asp:QueryStringParameter Name="UserID" QueryStringField="userid"
Type="String" DefaultValue="userid" />
<asp:QueryStringParameter DefaultValue="dtfrom" Name="dtfrom"
QueryStringField="dtfrom" Type="String" />
<asp:QueryStringParameter DefaultValue="dtto" Name="dtto"
QueryStringField="dtto" Type="String" />
</SelectParameters>
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 .......