Find Control In Datalist - c#

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;
}
}

Related

How to set 3 radiobutton with its groupname in a repeater

I need to set 3 different groups of radio button in a repeater. Using groupname property for it wasn't enough. So, after researching, I use a bit of JS and it works. My problem is when I want to implement more than one group of radiobuttons. Can anyone help me?
My best approach is:
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound">
<ItemTemplate>
<span>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
</span>
</ItemTemplate>
</asp:Repeater>
JS
<script>
function SetUniqueRadioButton(nameregex, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if (elm.type == 'radio') {
elm.checked = false;
}
}
current.checked = true;
}
</script>
CS
protected void repeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rbLogoSeleccionado");
RadioButton rbLogoSeleccionadoApp = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoApp");
RadioButton rbLogoSeleccionadoAppBlanco = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoAppBlanco");
string script = "SetUniqueRadioButton('repeaterImages.*nombreLogo',this)";
string scriptApp = "SetUniqueRadioButton('repeaterImages.*nombreLogoApp',this)";
string scriptAppBlanco = "SetUniqueRadioButton('repeaterImages.*nombreLogoAppBlanco',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
rbLogoSeleccionadoApp.Attributes.Add("onclick", scriptApp);
rbLogoSeleccionadoAppBlanco.Attributes.Add("onclick", scriptAppBlanco);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
With this code just getting 3 rows of radiobutton, sharing groupname behavior for all of them... (I want groupname behavior per row...)
Piece of cake. Prove how newie I am in JS. I am posting the solution because is a recurrent issue in asp programming and this bug is known. Beside I cant find the solution for some radio button.
JS.
<script>
function SetUniqueRadioButton(text, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if ((elm.type == 'radio') && (elm.value == text)) {
elm.checked = false;
}
}
current.checked = true;
}
</script>
CS
protected void repeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rbLogoSeleccionado");
RadioButton rbLogoSeleccionadoApp = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoApp");
RadioButton rbLogoSeleccionadoAppBlanco = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoAppBlanco");
string script = "SetUniqueRadioButton('rbLogoSeleccionado',this)";
string scriptApp = "SetUniqueRadioButton('rbLogoSeleccionadoApp',this)";
string scriptAppBlanco = "SetUniqueRadioButton('rbLogoSeleccionadoAppBlanco',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
rbLogoSeleccionadoApp.Attributes.Add("onclick", scriptApp);
rbLogoSeleccionadoAppBlanco.Attributes.Add("onclick", scriptAppBlanco);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound">
<ItemTemplate>
<span>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
</span>
</ItemTemplate>
</asp:Repeater>

Cant call Imagebutton in a OnCommand function

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;
}
}

How to find dropdown selected value inside repeater in dropdown selected index change event?

<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<tr>
<td><%#subtypes.FindByPk(Convert.ToInt32(Eval("SubitemID"))).title%></td>
<td><%#Eval("quantity")%></td>
<td><%#ThanaRecord.FindByPk(Convert.ToInt32(Eval("Thanaid"))).title%></td>
<td><%#Eval("created_at")%></td>
<td> <% if (Employee.GetCurrentEmployee().role == "Admin") { %>
EDIT
DELETE
<% } %>
<%if (Employee.GetCurrentEmployee().role == "SuperVisor")
{ %>
<asp:DropDownList ID="DropDownList1" runat="server" Width="120px" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" CssClass="form-control">
<asp:ListItem Text="Status" Value="0">Status</asp:ListItem>
<asp:ListItem Text="Accept" Value="1">Accept</asp:ListItem>
<asp:ListItem Text="Reject" Value="2">Reject</asp:ListItem>
</asp:DropDownList>
<%--<asp:textbox runat="server" id="textTest"></asp:textbox>--%>
</td>
<%} %>
</tr>
</ItemTemplate>
</asp:Repeater>
Code:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//DropDownList DropDownList1 = (DropDownList)sender;
//string SelectedValue = DropDownList1.SelectedValue;
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddldrop = (DropDownList)e.Item.FindControl("DropDownList1");
int value =Convert.ToInt32( ddldrop.SelectedValue);
Supervisor sup = new Supervisor();
if (value ==1 ) {
sup.Status = "Accept";
sup.Save();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Supervisor sup = new Supervisor();
//sup.Status = "Accept";
//sup.Save();
}
You just have to cast the sender argument in the event-handler to DropDownList. It is always the source of the event. So no need to use FindControl:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList) sender;
string selectedValue = ddl.SelectedValue;
// ...
}

Telerik Radgrid retrieve TextBox value that was dynamically added to column

From code I add a TextBox to a column
protected void grdPartsBeingMonitored_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem item = e.Item as GridDataItem;
foreach (GridColumn column in item.OwnerTableView.RenderColumns)
{
if (column.UniqueName == "MyColumn")
{
TextBox tbEditBox = new TextBox();
tbEditBox.Text = item[column].Text;
tbEditBox.Width = Unit.Pixel(50);
tbEditBox.ID = "editDemand";
item[column].Controls.Clear();
item[column].Controls.Add(tbEditBox);
}
}
}
Now how do I loop through each row and retrieve that rows value of the TextBox? Here's a start I believe:
foreach (GridDataItem item in grd1.MasterTableView.Items)
{
foreach (GridColumn column in item.OwnerTableView.RenderColumns)
{
if (column.UniqueName == "MyColumn")
{
//HOW TO RETRIEVE VALUE OF THE TEXTBOX HERE???
I tried this with no luck
foreach (Object c in item[column].Controls)
{
if (c.GetType() == typeof(TextBox))
{
TextBox tbEditBox = (TextBox)c;
System.Diagnostics.Debug.Write(tbEditBox.Text);
}
}
Please try with the below code snippet.
ASPX
<div>
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnNeedDataSource="RadGrid1_NeedDataSource" OnItemDataBound="RadGrid1_ItemDataBound">
<MasterTableView>
<Columns>
<telerik:GridBoundColumn DataField="ID" HeaderText="ID" UniqueName="ID"></telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="Name" DataField="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:Button ID="Button1" runat="server" Text="Show edit" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Get edit value" OnClick="Button2_Click" />
<asp:Button ID="Button3" runat="server" Text="hide edit" OnClick="Button3_Click" />
</div>
ASPX.CS
public bool IsEditable
{
get
{
if (ViewState["IsEdit"] == null)
return false;
else
return (bool)ViewState["IsEdit"];
}
set
{
ViewState["IsEdit"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "Name1");
dt.Rows.Add(2, "Name2");
dt.Rows.Add(3, "Name3");
RadGrid1.DataSource = dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
IsEditable = true;
RadGrid1.Rebind();
}
protected void Button2_Click(object sender, EventArgs e)
{
foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
{
Response.Write((item.FindControl("txtName") as TextBox).Text);
//perform your DB update here
}
}
protected void Button3_Click(object sender, EventArgs e)
{
IsEditable = false;
RadGrid1.Rebind();
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem item = e.Item as GridDataItem;
Label lblName = item.FindControl("lblName") as Label;
TextBox txtName = item.FindControl("txtName") as TextBox;
lblName.Visible = !IsEditable;
txtName.Visible = IsEditable;
}
}
Let me know if any concern.

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;
}
}
}

Categories

Resources