Cant call Imagebutton in a OnCommand function - c#

I have this in ASP.NET in VS
I have image button in repeater
<asp:Repeater ID="RepeaterImages" runat="server">
<ItemTemplate>
<asp:ImageButton ID="Imagebutton2" runat="server" CssClass="choicebutton" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "answer" )%>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "question" )%>' CommandName='<%# DataBinder.Eval(Container.DataItem, "answer" )%>' OnCommand="checkAnswer" />
</ItemTemplate>
</asp:Repeater>
and I want to change border color of image button when it is false
public void checkAnswer(object sender, CommandEventArgs e)
{
string trueanswer = e.CommandArgument.ToString();
string urlanswer = e.CommandName.ToString();
if (urlanswer == q_image)
{
}
else
{
// Imagebutoon2 doesnt exist in current context why?
Imagebutton2.BorderColor = Color.Red;
}
}

You can use ItemDataBound for this task:
protected void RepeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem))
{
Imagebutton Imagebutton2= (Imagebutton)item.FindControl("Imagebutton2");
string trueanswer = Imagebutton.CommandArgument.ToString();
string urlanswer = Imagebutton.CommandName.ToString();
if (urlanswer == q_image)
{
}
else
{
// Imagebutoon2 doesnt exist in current context why?
Imagebutton2.BorderColor = Color.Red;
}
}
}
Do not forget to add this to the repeater server tag: OnItemDataBound="RepeaterImages_ItemDataBound"
UPDATE
If you want this happen when imagebutton is clicked, then it is even more simple. You can use sender to access the imagebutton clicked:
public void checkAnswer(object sender, CommandEventArgs e)
{
ImageButton btn = (ImageButton)sender;
string trueanswer = e.CommandArgument.ToString();
string urlanswer = e.CommandName.ToString();
if (urlanswer == q_image)
{
}
else
{
// Imagebutoon2 doesnt exist in current context why?
btn.BorderColor = Color.Red;
}
}

Related

LinkButtons inside a Grid template to increment and decrement the lables value

protected void Gridproducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hp = new HyperLink();
hp = (HyperLink)e.Row.FindControl("linkSelectprd");
var Pid = DataBinder.Eval(e.Row.DataItem, "product_id").ToString();
var Catid = Request.QueryString["Cid"].ToString();
hp.NavigateUrl = "Sales.aspx?Cid="+Catid+"&"+"Pid="+Pid;
if (!IsPostBack && Request.QueryString["Pid"] != null)
{
this is the variable in which the value of quantity increments
int i=0;
lbltotalquantity.Text = i.ToString() + 1;
}
}
}
}
I use LinkButtons inside a Grid template. I want to be able to raise events when clicking the LinkButtons the value of lable is incremented on + link and decrementd on - link button as lable contains the quantity of Products added to invoice. How can I accomplish this?
I believe this is what you want....
You don't do the increment in RowDataBound because RowDataBound trigger when you are binding the GridView
.aspx
<asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="up" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:Label ID="lblProduct" runat="server" Text='<%# Eval("Product") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:Label ID="lblQuantity" runat="server" Text="0"></asp:Label>
<asp:LinkButton ID="lbtnPlus" runat="server" Text="+" OnClick="lbtnPlus_Click"></asp:LinkButton>
<asp:LinkButton ID="lbtnMinus" runat="server" Text="-" OnClick="lbtnMinus_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gv" />
</Triggers>
</asp:UpdatePanel>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
string[] product = { "Dell", "Asus", "Acer", "Toshiba", "Fujishu", "VAIO" };
DataTable dt = new DataTable();
dt.Columns.Add("Product");
for (int i = 0; i < product.Length; i++)
dt.Rows.Add(product[i]);
gv.DataSource = dt;
gv.DataBind();
// Dispose
dt.Dispose();
}
}
private void DoTheMath(GridViewRow row, bool isAdd)
{
// Variable
bool isNumber = false;
int currentValue = 0;
// Find Control
Label lblQuantity = row.FindControl("lblQuantity") as Label;
// Check
if (lblQuantity != null)
{
// Check
if (lblQuantity.Text.Trim() != string.Empty)
{
isNumber = int.TryParse(lblQuantity.Text.Trim(), out currentValue);
// Check
if (isNumber)
{
// Is Add
if (isAdd)
currentValue++;
else
{
// Check cannot be less than 0
if (currentValue > 0)
currentValue--;
}
}
// Set to TextBox
lblQuantity.Text = currentValue.ToString();
}
}
}
protected void lbtnPlus_Click(object sender, EventArgs e)
{
// Get
LinkButton lbtn = sender as LinkButton;
GridViewRow row = lbtn.NamingContainer as GridViewRow;
DoTheMath(row, true);
}
protected void lbtnMinus_Click(object sender, EventArgs e)
{
// Get
LinkButton lbtn = sender as LinkButton;
GridViewRow row = lbtn.NamingContainer as GridViewRow;
DoTheMath(row, false);
}

How to set different visibility properties for repeated items

I Have a user custom control with a repeater that has a calendar and a button that should toggle visibility for each repeated calendar.
<asp:Repeater ID="DateRepeater" runat="server"
DataSourceID="DateSource" OnItemCommand="DateRepeater_ItemCommand" OnPreRender="DateRepeater_PreRender">
<ItemTemplate>
<tr>
<td class="auto-style8">
<asp:ImageButton ID="CalendarButtonRef" runat="server" ImageUrl="~/img/calendar.png" OnClick="ShowCalendar_Click" />
<asp:Calendar ID = "RefCalendar" Width="176" runat="server" OnSelectionChanged="Calendar_SelChanged"></asp:Calendar>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
In the codebehind I am trying to target the clicked image button on the same repeated item
protected void ShowCalendar_Click(object sender, ImageClickEventArgs e)
{
ImageButton btnSender = (ImageButton)sender;
String TragetCalendarID = btnSender.UniqueID.Remove(19) + "RefCalendar";
if (Page.IsPostBack)
{
Calendar TargetCalendar;
foreach (RepeaterItem rpt in DateRepeater.Items)
{
if (rpt.FindControl("RefCalendar").UniqueID == TragetCalendarID)
{
Trace.Write(rpt.FindControl("RefCalendar").UniqueID);
Trace.Write(rpt.FindControl("RefCalendar").GetType().ToString());
TargetCalendar = (Calendar)rpt.FindControl(TragetCalendarID);
if (TargetCalendar.Visible == false)
{
TargetCalendar.Visible = true;
}
}
else
{
TargetCalendar.Visible = false;
}
}
}
I manage to cast the target Calendar and in the trace I get the object as a calendar but when I try to get the visibility property it says that the object reference is not set to an instance of an object.
What is missing in my code?
This is how the function then works, if referring to the object by its ID with FindControl it works. I was trying to cast the object to a calendar and use it as as a variable but it doesn't work like that.
This is the working code
protected void ShowCalendar_Click(object sender, ImageClickEventArgs e)
{
ImageButton btnSender = (ImageButton)sender;
String TragetCalendarID = btnSender.UniqueID.Remove(19) + "RefCalendar";
if (Page.IsPostBack)
{
foreach (RepeaterItem rpt in DateRepeater.Items)
{
if (rpt.FindControl("RefCalendar").UniqueID == TragetCalendarID)
{
if (rpt.FindControl("RefCalendar").Visible == false)
{
rpt.FindControl("RefCalendar").Visible = true;
}
else
{
rpt.FindControl("RefCalendar").Visible = false;
}
}
}
}
}

LinkButton in GridView non-clickable if it ends in a certain filetype

How would I make this LinkButton in GridView non-clickable if it ends in a *.rpt filetype?
I'm not sure where and which conditions I should add.
Thanks in advance!
Brett
LinkButton
.ascx code
<asp:LinkButton runat="server" ID="lbFolderItem" CommandName="OpenFolder" CommandArgument='<%# Eval("Name") %>'></asp:LinkButton>
<asp:Literal runat="server" ID="ltlFileItem"></asp:Literal>
Code Behind
ascx.cs code
protected void gvFiles_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem as FileSystemItemCS;
if (item.IsFolder)
{
var lbFolderItem = e.Row.FindControl("lbFolderItem") as LinkButton;
lbFolderItem.Text = string.Format(#"<img src=""{0}"" alt="""" /> {1}", Page.ResolveClientUrl("~/Images/folder.png"), item.Name);
}
else
{
var ltlFileItem = e.Row.FindControl("ltlFileItem") as Literal;
if (this.CurrentFolder.StartsWith("~"))
ltlFileItem.Text = string.Format(#"{1}",
Page.ResolveClientUrl(string.Concat(this.CurrentFolder, "/", item.Name).Replace("//", "/")),
item.Name);
else
ltlFileItem.Text = item.Name;
}
}
}
protected void gvFiles_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "OpenFolder")
{
if (string.CompareOrdinal(e.CommandArgument.ToString(), "..") == 0)
{
var currentFullPath = this.CurrentFolder;
if (currentFullPath.EndsWith("\\") || currentFullPath.EndsWith("/"))
currentFullPath = currentFullPath.Substring(0, currentFullPath.Length - 1);
currentFullPath = currentFullPath.Replace("/", "\\");
var folders = currentFullPath.Split("\\".ToCharArray());
this.CurrentFolder = string.Join("\\", folders, 0, folders.Length - 1);
}
else
this.CurrentFolder = Path.Combine(this.CurrentFolder, e.CommandArgument as string);
PopulateGrid();
}
}

How to change Button control's text inside Repeater control and catch its click event

I am trying to create buttons using asp:repeater
This is what I have:
<asp:Repeater ID="rptQuery" runat="server">
<ItemTemplate>
<asp:Button runat="server" Text='<%this.GetDataItem().ToString() %>'
OnClick="Unnamed_Click" />
</ItemTemplate>
</asp:Repeater>
I have no idea how to change the button text to reflect the value obtained from rptQUery's source ( a list of strings) and the onclick event to refer to this particular button.
Any advice please?
You can use ItemDataBound event to maniupluate the binding and appearance of Button control.
Then use Command event of the Button control to capture the posted data.
ASPX
<asp:Repeater ID="rptQuery" runat="server"
OnItemDataBound="rptQuery_ItemDataBound">
<ItemTemplate>
<asp:Button runat="server" ID="Button1" OnCommand="Button1_Command" />
</ItemTemplate>
</asp:Repeater>
Code Behind
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var customers = new List<Customer>
{
new Customer {Id = 1, Name = "Jon"},
new Customer {Id = 2, Name = "Eric"}
};
rptQuery.DataSource = customers;
rptQuery.DataBind();
}
}
protected void rptQuery_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
var customer = e.Item.DataItem as Customer;
var button = e.Item.FindControl("Button1") as Button;
button.CommandName = customer.Id.ToString();
button.Text = customer.Name;
}
}
protected void Button1_Command(object sender, CommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandName);
// Do something with id
}
I would recommend adding a ItemDataBinding event and handling this in code like so:
<asp:Repeater ID="rptQuery" runat="server" OnItemDataBound="rptQuery_ItemDataBound">
<ItemTemplate>
<asp:Button id="btnUnnamed" runat="server" OnClick="Unnamed_Click" />
</ItemTemplate>
</asp:Repeater>
Then your method would look something like this.
protected void rptQuery_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var data = e.Item.DataItem as string;
var btnUnnamed = e.Item.FindControl("btnUnnamed") as Button;
if (btnUnnamed != null)
{
btnUnnamed.Text = data;
}
}
}

Find Control In Datalist

When I tried To Find Control n data List As I Mentioned Below
Error(Object reference not set to an instance of an object.
I cannot know
protected void dlCategory_ItemDataBound(object sender, DataListItemEventArgs e)
{
Label Lb = (Label)e.Item.FindControl("LblCat");
Lb.ForeColor = System.Drawing.Color.Red;
}
<Datalist>
<asp:DataList ID="dlSubCategory" runat="server"
DataSource='<%# GetSubCategory(Convert.ToString(Eval("Category_ID")))%>'
onitemcreated="dlSubCategory_ItemCreated"
onitemdatabound="dlSubCategory_ItemDataBound">
<EditItemStyle ForeColor="#CC3300" />
<SelectedItemStyle ForeColor="#CC3300" />
<ItemTemplate>
<div class="buttn_div_sub">
<div class="lm40 tm2 buttn_txt">
<a href='<%# Convert.ToString(Eval("ProductCategory_Id")).Insert(0,"ListView.aspx?ProductCategory_Id=") %>'
class="buttn_txt">
<asp:Label ID="Label1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Name") %>'></asp:Label>
</a>
</div>
</div>
</ItemTemplate>
</asp:DataList>
</ItemTemplate>
protected void dlCategory_ItemDataBound(object sender, DataListItemEventArgs e)
{
Label Label1 = e.Item.FindControl("Label1") as Label;
if (LblCat != null)
{
string id = ((System.Data.DataRowView)e.Item.DataItem).Row["ProductCategory_Id"].ToString();
if (Request.QueryString["ProductCategory_Id"] == id)
{
Label1.ForeColor = System.Drawing.Color.Red;
}
}
}
Could you try this? The first item passed to this function will be the header (if present on the datalist) and that's why you get the error.
protected void dlCategory_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label Lb = (Label)e.Item.FindControl("LblCat"); Lb.ForeColor = System.Drawing.Color.Red;
}
}

Categories

Resources