ASPX
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Themes] WHERE ([Theme] = #Theme) ORDER BY [Price]">
<SelectParameters>
<asp:Parameter DefaultValue="Dubai-and-Beyond" Name="Theme" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:ListView ID="theme5" runat="server" DataSourceID="SqlDataSource5">
<LayoutTemplate>
<div id="itemPlaceHolderContainer" runat="server">
<span id="itemPlaceHolder" runat="server"></span>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<asp:Image ID="Destinationimage" runat="server"
ImageUrl='<%# Eval("ID", "~/CMS/ThemesHandler.ashx?ID={0}")+"&img=1"%>'
AlternateText="Destination_Image" Height="140px" Width="179px" />
<asp:Label ID="lblcountry" runat="server" Text='<%#Eval("Country") %>' />
</div>
<div class="hotel_name">
<asp:Label ID="lblcountry" runat="server" Text='<%#Eval("Country") %>' /></div>
<asp:ImageButton ID="imgbtn5" runat="server" ImageUrl="images/book_nw.png"
OnClick="imgbtn5_Click" AlternateText="get_quote"/></div>
</ItemTemplate>
</asp:ListView>
Code behind
protected void imgbtn5_Click(object sender, EventArgs e)
{
ListViewItem item = theme5.Items[0];
Label country = (Label)item.FindControl("lblcountry");
string con = country.Text.ToString();
Session["country"] = con.ToString();
Response.Redirect("Get_Quote.aspx");
}
Here, Theme5 is Listview. There is a Label and imgbutton in EACH listview item.
I want to transfer label value on imgbutton click event.
Problem here is i am not able to identify Row index of listview item.
You can make use of CommandName and CommandArgument of your ImageButton within your ListView. You may than access the according item from within your ItemCommand event.
<asp:ImageButton ID="imgbtn5" runat="server" ImageUrl="images/book_nw.png"
OnClick="imgbtn5_Click" AlternateText="get_quote"
CommandName="YOUR_COMMAND_NAME"
CommandArgument='<%#Eval("ANY_COLUMN_OF_SOURCE") %>' />
And within your codeBehind file
protected void theme5_OnItemCommand(object sender, ListViewCommandEventArgs e)
{
if (String.Equals(e.CommandName, "YOUR_COMMAND_NAME"))
{
string arg = e.CommandArgument; // do whatever you want
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
}
}
Related
I have a ASP.NET ListView inside an UpdatePanel.
In the ItemTemplate there are 2 buttons with Commands "UpdateCart" & "RemoveCart".
In both the commands, the datasource of ListView (an SQL DataSource) gets rebound.
There is no InsertCommand/UpdateCommand/DeleteCommand on the SqlDataSource
My problem is :
Whenver these buttons are clicked : the datasource does not get refreshed.
however I can see from debug mode that values are indeed passed to the datasource selecting method correctly.
The relevant ASPX Page :
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdateProgress ID="UpdateProgress1" DisplayAfter="10" runat="server" AssociatedUpdatePanelID="UpnlMain">
<ProgressTemplate>
<div class="divWaiting">
<asp:Label ID="lblWait" runat="server" Text=" Please wait... " />
<asp:Image ID="imgWait" runat="server" ImageAlign="Middle" ImageUrl="~/Image/AjaxLoading.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpnlMain" runat="server">
<ContentTemplate>
<asp:ListView ID="lvMain" runat="server" DataSourceID="sdsMain" DataKeyNames="Code"
OnItemCommand="lvMain_ItemCommand">
<EmptyDataTemplate>
<div class="col-xs-12">
<span>No Items in Cart.</span>
</div>
</EmptyDataTemplate>
<ItemTemplate>
<asp:Label ID="lblCode" runat="server" Text='<%# Eval("Code") %>' Visible="false" />
Product " <asp:Literal ID="ltrStyleNo" runat="server" Text='<%# Eval("StyleNo") %>' />
Qty : <asp:TextBox ID="txtQty" runat="server" type="number" CssClass="txtQty OnlyNumeric form-control text-center input-sm"
Text='<%# Eval("Qty") %>'></asp:TextBox>
<asp:ImageButton ID="btnUpdate" runat="server" ImageUrl="~/image/update.png" CssClass="btn btnUpdateCart"
CommandName="UpdateCart" AlternateText="Update Qty" />
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~/image/delet.png" CssClass="btn"
CommandName="DeleteCart" AlternateText="Remove Item" />
</ItemTemplate>
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</LayoutTemplate>
</asp:ListView>
<asp:SqlDataSource ID="sdsMain" runat="server" ConnectionString="<%$ ConnectionStrings:CurrentConnectionString %>"
SelectCommand="pGetItemsForCart" SelectCommandType="StoredProcedure" OnSelecting="sdsMain_Selecting"
UpdateCommand="NoUpdate" UpdateCommandType="StoredProcedure">
<UpdateParameters>
<asp:Parameter DefaultValue="-1" Name="WoSCodeCSV" Type="String" />
</UpdateParameters>
<SelectParameters>
<asp:Parameter DefaultValue="-1" Name="WoSCodeCSV" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
The Code Behind Code :
protected void sdsMain_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
e.Command.Parameters[0].Value = GetCartCodes(); //gives some values in csv from Session ..
}
protected void lvMain_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName.ToLower() == "UpdateCart".ToLower())
{
Label lblCode = e.Item.FindControl("lblCode") as Label;
TextBox txtQty = e.Item.FindControl("txtQty") as TextBox;
//Some update in a Session
BindListView();
}
else if (e.CommandName.ToLower() == "DeleteCart".ToLower())
{
Label lblCode = e.Item.FindControl("lblCode") as Label;
//Some update in a Session
BindListView();
}
else if (e.CommandName.ToLower() == "RefreshCart".ToLower())
{
Label lblCode = e.Item.FindControl("lblCode") as Label;
BL.StyleSearchHelper.PriceItem(Page, lblCode.Text);
BindListView();
}
}
void BindListView()
{
sdsMain.DataBind();
lvMain.DataBind();
}
Try replace your buttons outside the updatepanel. Page will not getting refresh when the buttons are in updatepanel. sorry i can't make comment so I post here as an answer.
I have a linqdatasource witch perform a ListView1 list. The listview change when the user select a doctor name from a Dropdownlist. I attached a OnSelectedIndexChanged="ListView1_SelectedIndexChanged" event to it.
The column of the listview1 are apointmentId, doctorName, dateApointment, clientName and a checkbox.
I want to update the row which got selected by the checkbox (basically the user selected a date for his apointment).
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="ApointmentDataContext"
EnableDelete="True" EnableInsert="True" EnableUpdate="True" EntityTypeName=""
TableName="Apointment" AutoGenerateWhereClause="True">
<WhereParameters>
<asp:ControlParameter
Name="doctorName"
ControlID="DropDownList1"
PropertyName="SelectedValue"
Type="String" />
</WhereParameters>
</asp:LinqDataSource>
<div class="center">
<asp:Label ID="lblDoctorName" runat="server" Text="Choose a doctor name"> </asp:Label>
<div class="value-right">
<asp:DropDownList ID="DropDownList1" runat="server" Width="180px" AutoPostBack="true" >
<asp:ListItem Text="Doctor A" Value="Doctor A" />
<asp:ListItem Text="Doctor B" Value="Doctor B" />
<asp:ListItem Text="Doctor C" Value="Doctor C" />
</asp:DropDownList>
</div>
</div> <br/><br/>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="apointmentId"
DataSourceID="LinqDataSource1" InsertItemPosition="LastItem"
OnSelectedIndexChanged="ListView1_SelectedIndexChanged" >
<AlternatingItemTemplate>
<tr style="">
<td>
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
</td>
<!--<td>
<asp:Label ID="ApointmentIdLabel" runat="server" Text='<%#
Eval("ApointmentId") %>' />
</td> -->
<td>
<asp:Label ID="doctorName" runat="server" Text='<%# Eval("doctorName") %>' />
</td>
<td>
<asp:Label ID="dateLabel" runat="server" Text='<%# Eval("dateApointment", "{0:dd-MM-
yyyy}") %>' />
</td>
<td>
<asp:Label ID="ClientLabel" runat="server" Text='<%# Eval("clientName") %>' />
</td>
<input id="MyCheckBox" value='<%# Eval("apointmentId") %>'
type="checkbox" runat="server" />
The following code will list all the available dates from the selected doctors. The goal is the user will select an available date (by checking the checkbox). Now I want to be able to update this row in the apointement table. I am missing the code to be able to use the ListView1 properties.
protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
{
using (ApointmentDataContext db = new ApointmentDataContext())
{
Listview1.
}
}
When I put ListView1 here I got the error message The name ListView1 does not exist in the current context.
I will like to be able to retrieve the guid or the ApointmentId to be able to update the selected row.
I got the checkbox selection by doing this. Maybe we can do something here ?
protected void btnSubmit_Click(object sender, EventArgs e)
{
int iCptCheckBox = 0;
int indxChkBox = 0;
foreach (ListViewDataItem item in ListView1.Items)
{
var chk = item.FindControl("MyCheckBox") as System.Web.UI.HtmlControls.HtmlInputCheckBox;
if (chk != null && chk.Checked)
{
indxChkBox = Convert.ToInt32(chk.Value);
iCptCheckBox++;
}
}
}
Thanks for your help to guide me to resolve my issue.
I believe you have two issues here:
That your listview is not visible in your code behind, to solve this please clean up your page designer.cs file and make a small change ( could add a space) in aspx, and regenerate the designer file. This should solve this issue.
Second issue getting the selected item, you should use SelectedDataKey property of listview to get the selected id. I can see that you have appointmentid as the datakey name.
I have added the error to this question's title.
I get an error with the below code. Input string was not in a correct format.
The error happens on this line:
int index = Convert.ToInt32(e.CommandArgument.ToString());
How do I resolve this error?
The aspx page:
<asp:Content ID="MyMainPage" ContentPlaceHolderID="MMain" Runat="Server">
<div id="awindow" >
<asp:Panel ID="Panel1" runat="server" CssClass="main">
<div style="width: 100%; float: left">
<asp:TextBox runat="server" style="margin-left:5px; float:left;" ID="newauthor" />
<asp:ImageButton runat="server" ID="addauthor" Height="17px" ToolTip="Add a new author" ImageUrl="~/siteimages/Addbuttons/add.png" OnClick="AddAuthor_Click"/>
<asp:TextBox runat="server" ID="txtAuthor" Text='<%# Bind("Author") %>' />
<asp:Button ID="btnFindAuthor" runat="server" Text="Author Quick Find" CommandName="Select" OnCommand="btnFindAuthor_Click" />
<ajaxToolkit:AutoCompleteExtender ID="authors" runat="server" DelimiterCharacters="" Enabled="True" ServicePath="~/WebServices/authorsearchdisplay.asmx" ServiceMethod="AutoComplete" TargetControlID="authors" MinimumPrefixLength="3" />
</div>
<asp:SqlDataSource runat="server" ID="sqlAuthors" ConnectionString="<%$ ConnectionStrings:Libro %>" ProviderName="<%$ ConnectionStrings:Libro.ProviderName %>"
SelectCommand="SELECT * FROM Authors"
InsertCommand="authors_GetOrCreate" InsertCommandType="StoredProcedure">
<InsertParameters>
<asp:ControlParameter ControlID="newAuthor" Name="authorame" />
</InsertParameters>
</asp:SqlDataSource>
<asp:GridView runat="server" ID="gvAuthors" DataSourceID="sqlAuthors" DataKeyNames="AuthorID" AutoGenerateColumns="false">
<Columns>
<asp:HyperLinkField HeaderText="Author Name" DataNavigateUrlFormatString="~/authors.aspx?id={0}" DataNavigateUrlFields="AuthorID" DataTextField="AuthorName" />
</Columns>
</asp:GridView>
</asp:Panel>
</div>
<div>
</div>
</asp:Content>
The script:
protected void btnFindAuthor_Click(object sender, CommandEventArgs e)
{
if (e.CommandName == "Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument.ToString());
// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = gvAuthors.Rows[index];
}
}
You need to assign CommandArgument to button.
Otherwise, int index = Convert.ToInt32(e.CommandArgument.ToString()); will throw exception.
For example -
<asp:Button ID="btnFindAuthor" runat="server" Text="Author Quick Find"
CommandName="Select"
OnCommand="btnFindAuthor_Click"
CommandArgument='<%# Bind("ID") %>' />
Assuming it's an error when casting from string to int, try:
const int DefaultIndexValue = 1;
int index;
if (!Int32.TryParse(e.CommandArgument.ToString(), out index))
{
index = DefaultIndexValue;
}
<asp:DataList ID="DataList2" runat="server" DataSourceID="SqlDataSource2" onitemcommand="DataList2_ItemCommand">
<ItemTemplate>
<div class="style49">
<table style="width:100%;">
<tr>
<td class="style50">
<asp:Image ID="Image3" runat="server" Height="61px"
ImageUrl='<%# Eval("F_Image") %>' Width="48px" />
</td>
<td>
<asp:LinkButton ID="LinkButton3" runat="server" Height="25px"
TabIndex="1" Text='<%# Eval("Name") %>'
Width="92px" CommandName="view_frnd">
</asp:LinkButton>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Friends] WHERE ([Email] = #Email)">
<SelectParameters>
<asp:SessionParameter Name="Email" SessionField="uid" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
protected void DataList2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "view_frnd")
{
Response.Write(e.CommandName.ToString());
}
}
Is succsessfully execute but I want to text of linkbutton that's bind with database table field. How can I access linkbutton3 text?
protected void DataList2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "view_frnd")
{
// get the link button in the row selected
LinkButton LinkButton3 = (LinkButton)e.Item.FindControl("LinkButton3");
// get its text
Response.Write(LinkButton3.Text);
}
}
If what you want is access to the value, then you should be able to bind the same value to the CommandArgument property of your LinkButton, and it will show up as the CommandArgument value in the DataListCommandEventArgs of the DataList's event arguments when the button is clicked.
CommandArgument='<%# Eval("Name") %>'
In your event handler, you would access it as:
protected void DataList2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "view_frnd")
{
Response.Write(e.CommandArgument);
}
}
i have a radio button list that on selecting, queries a table and displays data in a textarea. now i'm trying to enhance my code so that the value of the radio button is displayed within the URL. that way i can send users links to content displayed by the radio selection (i.e. articles).
So far i've been able to place the "Article_PK" within the url successfully when the user makes a selection. now i'm just stuck on how to get my databind working again. so basically, i need to read in the value of the "Article_PK" in the url to display the data within the textarea. need someone with some mad coding skills to save the day!
code behind --------
public partial class frm_Articles : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
RadioButtonList1.SelectedIndex = 0;
RadioButtonList1.DataBind();
}
else
{
string strRedirect;
strRedirect = "frm_Articles.aspx?Article_PK=" + RadioButtonList1.SelectedValue.ToString();
Response.Redirect(strRedirect);
}
}
protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
//
}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
try{
e.Command.Parameters["#URL_FK"].Value = Session["URL_PK"];
}
catch (Exception ex)
{
}
}
}
----- aspx
<tr valign="top">
<td width="75%">
<!-- Body -->
<asp:DetailsView ID="DetailsView3" runat="server" AutoGenerateRows="False" DataSourceID="SqlDataSource2" Height="100%" Width="100%" GridLines="None">
<Fields>
<asp:TemplateField HeaderText="ArticleText" ShowHeader="False" SortExpression="ArticleText">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ArticleText") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="*"></asp:RequiredFieldValidator>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ArticleText") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="*"></asp:RequiredFieldValidator>
</InsertItemTemplate>
<ItemTemplate>
<%# Eval("ArticleText") %>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:CSFConnectionString %>" SelectCommand="SELECT [ArticleText], [Title] FROM [TEST_Article] WHERE ([Article_PK] = #Article_PK)" onselecting="SqlDataSource2_Selecting">
<SelectParameters>
<asp:ControlParameter ControlID="RadioButtonList1" DefaultValue="1" Name="Article_PK" PropertyName="SelectedValue" Type="Int32" ConvertEmptyStringToNull="True" />
</SelectParameters>
</asp:SqlDataSource>
</td>
<td width="25%" align="left" valign="top">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TESTConnectionString %>" SelectCommand="SELECT Article_PK, ArticleText, Score, Title, Url_FK FROM TEST_Article WHERE (Url_FK = #URL_FK)" onselecting="SqlDataSource1_Selecting">
<SelectParameters>
<asp:Parameter DefaultValue="0" Name="Url_FK" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<h2>Articles</h2>
<h2>Select an article below:</h2>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="Title" DataValueField="Article_PK">
</asp:RadioButtonList>
<br />
</td></tr>
If you didn't build anything in your PageLoad event to handle the query string, then nothing will happen when the controls does a postback.
Inside your pageLoad event you want something like:
if(IsPostBack)
{
if(Request.QueryString["URL_PK"] != null)
{
int url_pk;
if(int.TryParse(Request.QueryString["URL_PK"].ToString(), out url_pk)
{
//do whatever you need to do with url pk here
}
}
Set your radio buttons to have autopostback="true" and you should get the desired effect.