Adding value to TextBox inside Datalist ItemTemplate - asp.net

I am creating an application, in which I am displaying the images(contained in a folder) in a datalist. Each datalist cell is having a ImageButton(clicking on which will show large pic of the image), a delete button(clicking which will delete the image), a edit button and a textbox. Clicking on the edit button will cause the imagefile name to get displayed in the textbox.
here is my .aspx code
<asp:DataList ID="dtlist" runat="server" RepeatColumns="4" CellPadding="5" EnableViewState="True">
<ItemTemplate>
<asp:ImageButton Width="100" ID="ImagePic" ImageUrl='<%# Container.DataItem %>' CommandName='<%# Container.DataItem %>' runat="server" OnClick="ImagePic_Click" ImageAlign="Top">
</asp:ImageButton>
<br />
<asp:Button Width="100" ID="btn_image_del" CommandName='<%# Container.DataItem %>' runat="server" Text="Delete" OnClick="btn_image_del_Click">
</asp:Button>
<br />
<asp:TextBox ID="txt_image_name" Width="100" runat="server" Visible="True" Text='<%# Container.DataItem %>' MaxLength="500" />
</asp:TextBox>
<asp:Button Width="100" ID="btn_image_edit" CommandName='<%# Container.DataItem %>' runat="server" Text="Edit" OnClick="btn_image_edit_Click">
</asp:Button>
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center" VerticalAlign="Bottom" />
</asp:DataList>
And the .cs code is as follows
protected void BindDataList()//shows the pics from the user folder
{
string[] list = Directory.GetFiles(Server.MapPath("/Candidate_Pics/" + Convert.ToString(Session["Sex"]) + "/" + txt_u_name.Text + "/"));
var aList = from fileName in Directory.GetFiles(Server.MapPath("/Candidate_Pics/" + Convert.ToString(Session["Sex"]) + "/" + txt_u_name.Text + "/"))
select string.Format("/Candidate_Pics/" + Convert.ToString(Session["Sex"]) + "/" + txt_u_name.Text + "/{0}", Path.GetFileName(fileName));
dtlist.DataSource = aList;
dtlist.DataBind();
}
protected void ImagePic_Click(object sender, ImageClickEventArgs e)
{
string strImage = ((ImageButton)sender).CommandName;
ViewState["InsertedURL"] = strImage;
ScriptManager.RegisterStartupScript(Page, typeof(Page), "ShowValidation", "javascript:ShowPic();", true);
Large_Pic.ImageUrl = strImage;
}
protected void btn_image_del_Click(object sender, EventArgs e)
{
string del_selected_image = ((Button)sender).CommandName;
File.Delete(Server.MapPath(del_selected_image));
}
protected void btn_image_edit_Click(object sender, EventArgs e)
{
string edit_selected_image = Path.GetFileName(((Button)sender).CommandName);
// Now what should i do:
}
The above three function namely ImagePic_Click,btn_image_del_Click, btn_image_edit_Click are working fine..Deletion, then LargePic view are all working perfectly, my problem is that, I want that when the edit button will be clicked, the corresponding name of the image will be displayed in the Datalist textbox. In the just above function, edit_selected_image is holding the filename of the corresponding image. I have tested it by applying breakpoints. Now the problem is that I want this value should be passed to the textbox "txt_image_name" in the Datalist.

Try this:
TextBox txt =(TextBox)dtlist.FindControl("txt_image_name");
txt.Text = edit_selected_image;

you need to use EditItemTemplate, for editing Edit Template.
you can write your mark up some tihing like this .
<EditItemTemplate>
PictureName:<asp:Label id="PicutreLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "yourFIleNamePath") %>' runat="server"/> <br />
<asp:LinkButton id="UpdateButton" Text="Update" CommandName="Update" runat="server"/>
<asp:LinkButton id="DeleteButton" Text="Delete" CommandName="Delete" runat="server"/>
<asp:LinkButton id="CancelButton" Text="Cancel" CommandName="Cancel" runat="server"/>

Related

Gridview Delete Linkbutton not firing RowDeleting Event

I am so frustrated. Using asp.net GridView. Using a LinkButton with the CommandName="Delete". Don't understand why the page isn't posting back. I've done this a million times in other apps. I've compared them against one another and nothing appears different. I will preface by saying this IS someone else's template, however, so it's not my same template.
Any ideas what might be causing my issues?
My scenario is this:
ASPX Page (edited to add the HTML; there's more HTML in the site.Master and there's also a tag for the AjaxControlToolkit at the top of the page):
<div class="width80 container body-content">
<h2 class="marginTop50">Message Board</h2>
<asp:Panel ID="pnlMsgsForUser" runat="server" Visible="false">
<div class="jumbotronSmallFont">
<asp:Label ID="lblErrorMessage" CssClass="has-error" runat="server"></asp:Label>
</div>
</asp:Panel>
<div class="jumbotronSmallFont">
<h4>New Message</h4>
<form>
<div class="form-group">
<label for="messageBody">Message Body</label>
<textarea class="form-control" id="messageBody" rows="3" style="max-width: 600px;"></textarea>
</div>
<div class="text-center">
<button id="btnSave" class="btn btn-primary" style="width: 75px;">Save</button>
<button type="button" id="btnReset" class="btn btn-default marginLeft15px" style="width: 75px;">Reset</button>
</div>
</form>
</div>
<div>
<asp:GridView ID="gvMessages" runat="server" Width="100%"
CssClass="table adminMessageBoardTable marginAuto" AutoGenerateColumns="False"
OnRowUpdating="gvMessages_RowUpdating"
OnRowCancelingEdit="gvMessages_RowCancelingEdit"
OnRowDataBound="gvMessages_RowDataBound"
OnRowEditing="gvMessages_RowEditing"
OnRowDeleting="gvMessages_RowDeleting"
DataKeyNames="Id" BorderStyle="NotSet">
<Columns>
<asp:TemplateField HeaderText="Message" HeaderStyle-CssClass="center" SortExpression="Message">
<EditItemTemplate>
<asp:TextBox ID="txtMsg" Width="100%" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("MessageBody") %>' ID="lblMessage"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Updated" SortExpression="DateUpdated" HeaderStyle-CssClass="center" ItemStyle-CssClass="center">
<HeaderStyle Width="120px" />
<EditItemTemplate>
<asp:Label runat="server" ID="lblEditDateUpdated" Enabled="false"></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("DateUpdated","{0:d}") %>' ID="lblDateUpdated"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Updated By" SortExpression="UpdatedBy" HeaderStyle-CssClass="center" ItemStyle-CssClass="center">
<HeaderStyle Width="120px" />
<EditItemTemplate>
<asp:Label runat="server" Text="" ID="lblEditUpdatedBy" Enabled="false"></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("UpdatedBy") %>' ID="lblUpdatedBy"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="center">
<HeaderStyle Width="120px" />
<EditItemTemplate>
<asp:LinkButton ID="lbUpdate" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"
OnClientClick="return confirm('You are about to update this entry. \n\nDo you wish to proceed?');"></asp:LinkButton>
<asp:LinkButton ID="lbCancel" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="lbEdit" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="lbDelete" runat="server" CommandArgument='<%# Eval("Id") %>' CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="return confirm('You are about to delete this entry. \n\Do you wish to proceed?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
In my code-behind, I have:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var user = CommonFunctions.GetUserID(true);
var Admin = Roles.IsUserInRole(user, "Administrator");
var Dev = Roles.IsUserInRole(user, "Developer");
if (!Admin && !Dev)
{
Response.Redirect("~/");
}
gvBind(true);
}
}
When I click on the Delete linkbutton for a row, it drops into the Page_Load and
!Page.IsPostBack
verifies as true. I have no idea why it's doing this. It also never even hits the RowDeleting command. My breakpoint is so sad.
In my other app, all the markup and code-behind are pretty much the same. The only differences are the gridview name and the Eval tags. But when I click Delete in that app, it skips the !Page.IsPostBack section. :( It also obviously fires the RowDeleting.
I've also tried implementing RowCommand, but that event never fires either. It only does Page_Load and RowDataBound before essentially refreshing the page.
Any ideas?
Please, and thanks!!!
Your code is working fine. When I click Delete button, it triggers gvMessages_RowDeleting event. Here is how I test it -
<asp:GridView ID="gvMessages" runat="server" Width="100%"
CssClass="GridView marginAuto" AutoGenerateColumns="False"
OnRowDeleting="gvMessages_RowDeleting"
DataKeyNames="Id">
<Columns>
<asp:TemplateField HeaderText="Message" HeaderStyle-CssClass="center" SortExpression="Message">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("MessageBody") %>' ID="lblMessage"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="center">
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CommandArgument='<%# Eval("Id") %>' CausesValidation="False"
CommandName="Delete" Text="Delete"
OnClientClick="confirm('You are about to delete this entry. \n\Do you wish to proceed?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
public class Item
{
public int Id { get; set; }
public string MessageBody { get; set; }
}
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvMessages.DataSource = new List<Item>
{
new Item {Id = 1, MessageBody = "One"},
new Item {Id = 2, MessageBody = "Two"},
new Item {Id = 3, MessageBody = "Three"},
};
gvMessages.DataBind();
}
}
protected void gvMessages_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
}
OnClientClick="return confirm('Are you sure?');"
Try to add the return from your confirm statement.

How to change dynamic css style of button of datalist on DataBinding

<asp:DataList ID="DataList1" runat="server" RepeatColumns="5" RepeatDirection="Horizontal"
onitemcommand="DataList1_ItemCommand"
onselectedindexchanged="DataList1_SelectedIndexChanged"
ondatabinding="DataList1_DataBinding">
<ItemTemplate>
<asp:HiddenField ID="Hdnqid" runat="server" Value='<%# Bind("Id") %>' />
<asp:HiddenField ID="HidnResultStatus" runat="server" Value='<%# Bind("ResultStatus") %>' />
<asp:Button ID="Butto" runat="server" Text='<%#Eval("Id") %>' CommandName="Save&Next"
CommandArgument='<%#Eval("Id") %>' />
</ItemTemplate>
</asp:DataList>
I want to change color of button accourding to value of table.
One way of doing this is using OnDataBound event of the data list. In the event you can get the button as well as your data item properties. Here you can change the properties of the button as below
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
Button button = e.Item.FindControl("Butto") as Button;
HiddenField HidnResultStatus = e.Item.FindControl("HidnResultStatus") as HiddenField;
string property = DataBinder.Eval(e.Item.DataItem, "colorproperty") as string;
//Here you can change the button color based on the value
if(HidnResultStatus.Value=="")
button.ForeColor = System.Drawing.Color.Black;
if(HidnResultStatus.Value=="1")
button.ForeColor = System.Drawing.Color.Brown;
}

Can not get textbox value inside datalist

I am trying to get the value of textbox "Qty" inside a datalist. It does not work. What is wrong? I have both the CartItem label and the datelist inside the ajax updatepanel. Thanks for any help. Here is my code:
<asp:Label ID="CartItems" runat="server" Text="CartItem"></asp:Label>
<br />
<asp:DataList ID="DataList1" runat="server" CellPadding="10"
DataKeyField="product_id" DataSourceID="SqlDataSource1" RepeatColumns="2">
<ItemTemplate>
<asp:Label ID="product_id" runat="server"
Text='<%# Eval("product_id") %>' /><br/>
<asp:Label ID="product_name" runat="server"
Text='<%# Eval("product_name") %>' />
<br />
Qty
<br/>
<asp:TextBox ID="Qty" runat="server"></asp:TextBox>
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to Cart"
onClick="ButtonAddToCart_Click"/>
<br />
</ItemTemplate>
</asp:DataList>
and here is the button click event. The CartItem has null value:
protected void ButtonAddToCart_Click(object sender, EventArgs e)
{
CartItem.Text = DataList1.FindControl("Qty").ToString();
}
TextBox Qty = (TextBox)DataList1.FindControl("Qty");
if(Qty != null)
{
CartItem.Text =Qty.Text;
}
You can use NamingContainer or Parent to access sibling controls
protected void ButtonAddToCart_Click(object sender, EventArgs e)
{
var button = sender as Button;
var textbox = button.NamingContainer.FindControl("Qty") as TextBox;
CartItem.Text = textbox.Text;
}
I prefer you to use item_command event of the datalist
do some think like this.
<asp:Label ID="CartItems" runat="server" Text="CartItem"></asp:Label>
<br />
<asp:DataList ID="DataList1" runat="server" CellPadding="10" DataKeyField="product_id" DataSourceID="SqlDataSource1" RepeatColumns="2">
<ItemTemplate>
<asp:Label ID="product_id" runat="server"
Text='<%# Eval("product_id") %>' /><br/>
<asp:Label ID="product_name" runat="server"
Text='<%# Eval("product_name") %>' />
<br />
Qty
<br/>
<asp:TextBox ID="Qty" runat="server"></asp:TextBox>
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to Cart" CommandName="addtocart2" OnCommand="DataList1_ItemCommand"
/>
<br />
</ItemTemplate>
</asp:DataList>
Here is the item_command event that works.
public void DataList1_ItemCommand(object source, System.Web.UI.WebControls.CommandEventArgs e){
TextBox qtytxtbox = DataList1.FindControl("Qty") as TextBox;
}
You can do like this
protected void ButtonAddToCart_Click(object sender, EventArgs e)
{
Button ButtonAddToCart= (Button)sender;
DataListItem item = (DataListItem)ButtonAddToCart.NamingContainer;
var textbox = (TextBox)item.FindControl("Qty");
}
try this one
TextBox txtquantity = (TextBox)(e.Item.FindControl("Qty"));
simply use this......You will get the value in txtquantity

How do you get the DataKeyField from a Linkbutton inside a Datalist?

New to asp.net so any help would be great Thank you.
I have a Datalist with has product name, price, Image and a linkbutton inside a datalist it also holds ProductID which is not displayed.
How do you get the current productID from onClick event of the LinkButton thank you.
My DataList
<asp:DataList ID="dlProduct" runat="server" DataKeyField="ProductID" RepeatDirection="Horizontal" RepeatColumns="4" CellPadding="10" CellSpacing="10" >
<ItemTemplate>
<asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval("ProductName") %>' />
<br />Price:
<asp:Label ID="PriceLabel" runat="server" Text='<%# "$" + Eval("Price") %>' />
<br />
<asp:Image ID="Image1" runat="server" CssClass="ImageStyles" ImageUrl='<%# "GetImage.ashx?Id=" + Eval("PID") %>' BackColor="White" BorderStyle="Ridge" BorderColor="WhiteSmoke" />
<br />
<asp:LinkButton ID="btnAddToCart" OnClick="btnAddToCart_Click" runat="server"><img src="images/AddToCart.png" onmouseover="this.src='images/AddToCartMouseOver.png';" onmouseout="this.src='images/AddToCart.png';" /></asp:LinkButton>
</ItemTemplate>
</asp:DataList>
My Code behind
protected void btnAddToCart_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>alert('Product ID = "+ PID.Text + "');</script>", false);
}
Use the CommandArgument property of the LinkButton control.
Like:
<asp:LinkButton ID="btnAddToCart"
CommandName="AddToCart"
CommandArgument='<%# Eval("ProductId") %>'
OnCommand="btnAddToCart_Command" runat="server">
Then in the btnAddToCart_Command you can get command argument like this.
protected void btnAddToCart_Command(object sender, CommandEventArgs args)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>alert('Product ID = " + args.CommandArgument+ "');</script>", false);
}
Hope this helps.

Gridview under Repeater control in asp.net

i have a repeater control which contains grids, based on values from database, say for example i have 2 grids inside repeater control, now both the grids contains a column which have up and down buttons, now when user clicks on the button from any grids, how can i check from which grid the button is called.
below is my code where i am filling the grids on RepeaterItemDataBound Event
GridView gvw = e.Item.FindControl("grid") as GridView;
gvw.DataSource = info.GetStories(sectionNames[e.Item.ItemIndex].Trim());
gvw.DataBind();
here section name contains the name of the sections, based on number of sections, i generate the grids.
My Design looks like this:
<asp:Repeater ID="rptGrids" runat="server"
OnItemDataBound="rptGrids_ItemDataBound">
<ItemTemplate>
<asp:GridView ID="grid" runat="server" Width="100%" CellPadding="5" AllowPaging="true" ShowHeader="true" PageSize="10" AutoGenerateColumns="false" OnRowCommand="Stories_RowCommand">
<Columns>
<asp:BoundField DataField="ArticleID" HeaderText="Article ID" ItemStyle-CssClass="center" />
<asp:BoundField DataField="CategoryID" HeaderText="Category ID" ItemStyle-CssClass="center" />
<asp:BoundField DataField="Title" HeaderText = "Article Title" />
<asp:BoundField DataField="PublishDate" DataFormatString="{0:d}" HeaderText="Publish Date" ItemStyle-CssClass="center" />
<asp:TemplateField HeaderText="Select Action" ItemStyle-CssClass="center">
<ItemTemplate>
<asp:ImageButton ID="btnMoveUp" runat="server" ImageUrl="/images/up.gif" CommandArgument="Up" CommandName='<%# Container.DataItemIndex + "," + DataBinder.Eval(Container.DataItem, "StoryType") %>' />
<asp:ImageButton ID="btnMoveDown" runat="server" ImageUrl="/images/dn.gif" CommandArgument="Down" CommandName='<%# Container.DataItemIndex + "," + DataBinder.Eval(Container.DataItem, "StoryType") %>' />
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="/images/deny.gif" CommandArgument="Delete" OnClientClick="return confirm('Are you sure you want to delete this article?');" CommandName='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:HiddenField ID="hdStoriesSortOrder" runat="server" Value='<%# Eval("SortOrder") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div class="blank"></div>
</ItemTemplate>
</asp:Repeater>
this is my gridviews row_command event
protected void Stories_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandName.Split(',')[0]);
string section = e.CommandName.Split(',')[1].Trim().ToString();
string command = e.CommandArgument.ToString();
if (command.ToLower() == "up")
{
GridView grd = rptGrids.Items[1].FindControl("grid") as GridView; // If i specify the index here, i gets proper grid, but how to recognize at runtime.
Response.Write(grd.Rows.Count);
}
else if (command.ToLower() == "down")
{
}
}
can anyone tell me how can i get from which grid up/down button has been clicked.
You can use command argument to pass required value.
Here is sample of using imagebutton in similar way:
<asp:ImageButton ID="btnView" runat="server" ToolTip="<% $resources:AppResource,Edit %>"
SkinID="EditPage" CommandName="myCommand" CommandArgument='<%# Eval("CustomerId") %>'
PostBackUrl='<%# "~/AdminPages/Customer.aspx?id=" + Eval("CustomerId").ToString() %>' />
Take notice on CommandArgument property.You can set it with value that indicates specific gridview inside repeater.
And here is how to check the value:
protected void EntityGridViewContacts_RowCommand(object sender, GridViewCommandEventArgs e)
{
//here you can check for command name...
switch (e.CommandName)
{
case "myCommand":
//here you access command argument...
int customerId = Convert.ToInt32(e.CommandArgument.ToString());
break;
}
//here is how you access source gridview...
GridView gridView = (GridView)sender;
string controlId = gridView.ID;
}
You can also set CommandArgument using this approach:
CommandArgument='<%# GetMySpecialValue() %>'
Then you should declare function on page side something like this:
public string GetMySpecialValue()
{
return "some value";
}

Resources