The following code shows some checkboxes that if you choose any of them, it will be listed on the page.
The problem is that I want to use the "LinkButton" on the page that if I click on the link then the ckeckbox will be shown. When I use OnLoad="Page_Edit" in "asp:LinkButton", the checkboxlist works fine but I do not want the checkboxlist shows up all the time and I want it to show up by clicking on the "Click to work with checkbox!" link. if I use OnClick="Page_Edit", by choosing any of the checkboxes, the checkboxlist disappears. Any help would be appreciated.
<h3> CheckBoxList Constructor Example </h3>
<asp:LinkButton id="myid" runat="server" Text="Click to work with checkbox!" OnLoad="Page_Edit" OnClick="Page_Edit" /><br />
Select items from the CheckBoxList.
<br /><br />
<asp:PlaceHolder id="Place" runat="server"/>
<br /><br />
<asp:label id="Message" runat="server"/>
void Check_Clicked(Object sender, EventArgs e)
{
// Retrieve the CheckBoxList control from the Controls collection
// of the PlaceHolder control.
CheckBoxList checklist = (CheckBoxList)Place.FindControl("checkboxlist1");
// Make sure a control was found.
if(checklist != null)
{
Message.Text = "Selected Item(s):<br /><br />";
// Iterate through the Items collection of the CheckBoxList
// control and display the selected items.
for (int i=0; i<checklist.Items.Count; i++)
{
if (checklist.Items[i].Selected)
{
Message.Text += checklist.Items[i].Text + "<br />";
}
}
}
else
{
// Display an error message.
Message.Text = "Unable to find CheckBoxList control.";
}
}
void Page_Edit(Object sender, EventArgs e)
{
// Create a new CheckBoxList control.
CheckBoxList checklist = new CheckBoxList();
// Set the properties of the control.
checklist.ID = "checkboxlist1";
checklist.AutoPostBack = true;
checklist.CellPadding = 5;
checklist.CellSpacing = 5;
checklist.RepeatColumns = 2;
checklist.RepeatDirection = RepeatDirection.Vertical;
checklist.RepeatLayout = RepeatLayout.Flow;
checklist.TextAlign = TextAlign.Right;
// Populate the CheckBoxList control.
checklist.Items.Add(new ListItem("Item 1"));
checklist.Items.Add(new ListItem("Item 2"));
checklist.Items.Add(new ListItem("Item 3"));
checklist.Items.Add(new ListItem("Item 4"));
checklist.Items.Add(new ListItem("Item 5"));
checklist.Items.Add(new ListItem("Item 6"));
// Manually register the event-handling method for the
// SelectedIndexChanged event.
checklist.SelectedIndexChanged += new EventHandler(this.Check_Clicked);
// Add the control to the Controls collection of the
// PlaceHolder control.
Place.Controls.Add(checklist);
}
Get rid of OnLoad on the checkbox and linkbutton; OnLoad runs everytime and does not meet your condition of showing only when linkbutton clicked. Now if the items are always in the list everytime, I'd recommend just add the control to the markup:
<asp:CheckboxList .. Visible="false">
<Items>
<asp:ListItem Text="Item 1" />
</Items>
</asp:CheckBoxList>
Notice the visible property; in linkbutton onclick, then you set checkboxlistID.Visible = true, and it will appear to the user.
Better idea is to create a new CheckBoxList control on PageLoad method with IsPostBack checking.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
//create checkbox list
}
After that you should add only OnClick="Page_Edit" to link button and inside Page_Edit method try to change only Visible properties for example:
void Page_Edit(Object sender, EventArgs e)
{
if(yourCondition)
yourCheckBoxList.Visible = true;
else
yourCheckBoxList.Visible = false;
}
The solution would be to have both OnLoad and OnClick on "asp:linkButton" and in OnClick event we make the checklist visible. This way we have made the checkbox to be loaded to the page but invisible unless someone clicks on the link that makes it visible. Thank you all.
Related
I have a Repeater with a certain DataSource (consisting of a list of images). The Repeater holds ImageButtons.
The aspx:
<asp:Panel ID="panSearch" runat="server" ScrollBars="Vertical" BorderColor="#333333" BorderStyle="Inset" Width="500" Height="200">
<asp:Repeater ID="Repeater" runat="server">
<ItemTemplate>
<asp:ImageButton OnClick="imgSearchResult_Click" BackColor="#333333" ID="imgSearchResult" height="32" width="32" runat="server" ImageUrl='<%# Eval("ImageUrl") %>'/>
</ItemTemplate>
</asp:Repeater>
</asp:Panel>
Additionally, I have a TextBox, which has a TextChanged-event in code-behind. I do a few things in there and at the end, my Repeater's DataSource will be overwritten with a new List of images (those images are put into the ImageButtons).
Repeater.DataSource = ImageList;
Repeater.DataBind();
My problem: Whenever my Repeater.DataSource is changed, it "clicks" the first ImageButton inside the Repeater. How do I prevent that from happening?
Full code:
My TextBox:
<asp:TextBox ID="textSearch" runat="server" Width="80" OnTextChanged="textSearch_TextChanged" ForeColor="Black" />
My TextChanged event:
protected void textSearch_TextChanged(object sender, EventArgs e)
{
string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/ORAS"));
List<System.Web.UI.WebControls.Image> ImageList = new List<System.Web.UI.WebControls.Image>(filesindirectory.Count());
foreach (string item in filesindirectory)
{
System.Web.UI.WebControls.Image myImage= new System.Web.UI.WebControls.Image();
myImage.ImageUrl = (String.Format("~/Images/ORAS/{0}", System.IO.Path.GetFileName(item)));
ImageList.Add(myImage);
}
Repeater.DataSource = ImageList;
Repeater.DataBind();
}
When I click on an ImageButton inside the Repeater (which is executed when the text in my TextBox is changed):
protected void imgSearchResult_Click(object sender, ImageClickEventArgs e)
{
var selectedImage = sender as ImageButton;
if (img1.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img1.ImageUrl = selectedImage.ImageUrl;
}
else if (img2.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img2.ImageUrl = selectedImage.ImageUrl;
}
else if (img3.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img3.ImageUrl = selectedImage.ImageUrl;
}
else if (img4.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img4.ImageUrl = selectedImage.ImageUrl;
}
else if (img5.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img5.ImageUrl = selectedImage.ImageUrl;
}
else if (img6.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img6.ImageUrl = selectedImage.ImageUrl;
}
else
{
ErrorMessage("Please remove one Image first!", true);
}
}
Pageload:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
img1.ImageUrl = "~/Images/ORAS/Empty/000.png";
img2.ImageUrl = "~/Images/ORAS/Empty/000.png";
img3.ImageUrl = "~/Images/ORAS/Empty/000.png";
img4.ImageUrl = "~/Images/ORAS/Empty/000.png";
img5.ImageUrl = "~/Images/ORAS/Empty/000.png";
img6.ImageUrl = "~/Images/ORAS/Empty/000.png";
LoadImages();
}
}
(LoadImages is almost 1:1 what's in my TextChanged function)
I really am not sure how (why) ASP.NET WebForms does it, but if you hit Enter and the form posts back, it will find the first control that implements IPostBackEventHandler and execute whatever event is bound to that. ImageButton implements it and so that's why it keeps firing the click event even though you didn't click on it. And, once again, only if you hit Enter.
I think that behaviour happens because the data posted back - __EVENTTARGET and __EVENTARGUMENT - are empty. Then ASP.NET goes bonkers.
You can solve it by putting a dummy button at the top of the page (or masterpage) and hide it using the style attribute. so:
<asp:Button ID="dummy" runat="server" style="display:none" />
Then in the init or load of your page (or masterpage) put
Form.DefaultButton = dummy.UniqueID;
That will force the button to capture the enter press instead of the arbitrary image button.
I have a radio button list that contains 2 items right now.Here is the aspx code:
<asp:RadioButtonList ID="RadioButtonList1" runat="server" Font-Bold="True"
Height="52px" Width="181px" AutoPostBack="True" EnableTheming="True"
EnableViewState="true" onselectedindexchanged="RadioButtonList1_SelectedIndexChanged">
<asp:ListItem Value="Head of family "></asp:ListItem>
<asp:ListItem Value="Show all">All Family Members</asp:ListItem>
</asp:RadioButtonList>
On page load when the page is loaded for the first time,I have set the first radio button item as the selected item through the following code :
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
RadioButtonList1.Items[0].Selected = true;
}
}
catch (Exception ce)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ce.Message + "');", true);
}
}
But after all of this, the selectedindexchanged event does not fire.I tried setting the EnableViewState property to true for the radiobuttonlist as well as for the page.I also tried setting the first item as selected through the aspx code rather than doing it at page load, but nothing worked.What should be done?This is the selectedindexchanged event:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
The first item gets selected, there are no issues, but when I try to select the second element, nothing happens apart from a postback.
There seems to be an issue with the radio buttons.I tried adding two radio buttons to the page to see if they work or not.Even simple radio buttons are not responding to selections.However when I add checkboxes, they work alright.
If you select the item in the code behind, the event doesn't fire.
From MSDN:
The SelectedIndexChanged event is raised when the selection from the list control changes between posts to the server.
More informations here:
ListControl.OnSelectedIndexChanged Method
Remove onselectedindexchanged="RadioButtonList1_SelectedIndexChanged" from RadioButtonList control and try adding
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
in Page_Load outside of
if (!IsPostBack)
{
}
block. See if that works.
I'm adding dynamic text box's to my panel in page load event, But I'm not able to access text box's in button click event and it is showing panel controls count ZERO(0) in button click event. Please give me solution to access text box values in button click event .
Thanks in advise.
Add your control in the Init function:
<div id="Parent" runat="server">
</div>
<asp:Button ID="btnTest" runat="server" Text="Get text" OnClick="btnTest_Click" />
protected void Page_Init(object sender, EventArgs e)
{
TextBox textInput = new TextBox();
textInput.ID = "text1";
textInput.Text = "Test";
Parent.Controls.Add(textInput);
}
protected void btnTest_Click(object sender, EventArgs e)
{
Response.Write((Parent.FindControl("text1") as TextBox).Text);
}
Inside the EventHandler of the particular button
insert this
TextBox MyTextBox=new TextBox();
//Assigning the textbox ID name
MyTextBox.ID = "name" +""+ ViewState["val"] + i;
MyTextBox.Width = 440;
MyTextBox.Height = 40;
MyTextBox.TextMode = TextBoxMode.MultiLine;
this.Controls.Add(MyTextBox);
I have a repeater whose ItemTemplate contains a PlaceHolder that I add input controls (ListBox, TextBox, CalendarExtender etc.) to on ItemDataBound:
<asp:UpdatePanel ID="ReportParameterUpdatePanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Repeater ID="ReportParameterEditRepeater" OnItemDataBound="ReportParameterEditRepeater_ItemDataBound" runat="server">
<ItemTemplate>
<asp:PlaceHolder runat="server" ID="ParameterEntryPlaceholder"></asp:PlaceHolder>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
How can I generate an asyncpostback from one of these TextBoxes inside the repeater (on TextChanged)?
The control is created dynamically and I only want to create the postback under certain conditions, so it needs to be done from code behind.
I have tried:
OnItemCommand (but this appears to be just for buttons)
ScriptManager.RegisterAsyncPostBackControl (doesn't seem to do anything on TextChanged)
UpdatePanel.Triggers.Add(new AsyncPostBackTrigger ...) (unable to find the TextBox as it is inside the repeater)
In ReportParameterEditRepeater_ItemDataBound you will need to assign a unique ID to each control, and then bind the text changed event. I then like to store those in session. Then add it to your placeholder.
Below is how I did it in my site for a button click event:
TemplateControls_Headline ctrl = (TemplateControls_Headline)LoadControl("~/Controls/TemplateHeadline.ascx");
ctrl.ID = "MyCtrl_" + CMSSession.Current.AddedTemplateControls.Count;
ctrl.Remove.Click += new EventHandler(RemoveItem_OnClick);
MySession.Current.AddedTemplateControls.Add((Control)ctrl);
PlaceHolder ph = accAddTemplates.FindControl("phAddTemplateControlsArea") as PlaceHolder;
ph.Controls.Add(ctrl);
Then, in your OnInit of the page, you have to re-bind everything from the viewstate since you are creating them dynamically, this is where the unique id you created comes in (this is mainly for postbacks):
protected override void OnInit(EventArgs e)
{
PlaceHolder ph = accAddTemplates.FindControl("phAddTemplateControlsArea") as PlaceHolder;
int counter = 0;
foreach (UserControl ctrl in MySession.Current.AddedTemplateControls)
{
ctrl.ID = "MyCtrl_" + counter;
ctrl.Remove.CommandArgument = counter.ToString();
ctrl.Remove.Click += new EventHandler(RemoveItem_OnClick);
counter++;
ph.Controls.Add(ctrl);
}
base.OnInit(e);
}
On an ASP.NET page, I have a gridview which contains a dropdownlist in one of its columns. While other columns in the gridview are databound, the dropdown list is NOT, and only contains 3 preset values "Frank", "Yes", and "No". ("Frank" is used as an example so that I don't get false readings from my preferred blank option)
<asp:GridView ID="testGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Code1" HeaderText="Code1" />
<asp:BoundField DataField="Code2" HeaderText="Code2" />
<asp:TemplateField HeaderText="Like Frank?">
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlLikeFrank">
<asp:ListItem>Frank</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:HyperLinkField ... HeaderText="File" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="cmdUpdate" runat="server" Text="Update" OnClick="cmdUpdate_Click" /></div>
I don't need AutoPostBack on these dropdownlists, as I only want to consider their selected values when the button cmdUpdate is clicked.
protected void cmdUpdate_Click(object sender, EventArgs e)
{
bool likesFrank = false;
string selected = "";
DropDownList ddl = null;
GridViewRow current = null;
// Go through each row and check the dropdown list.
for (int i = 0; i < testGrid.Rows.Count; i++)
{
current = testGrid.Rows[i];
...
ddl = (DropDownList)(current.FindControl("ddlLikeFrank"));
/* THIS FOR LOOP IS WAS USED FOR INVESTIGATING THIS ISSUE*/
for (int j = 0; j < ddl.Items.Count; j++)
{
if (ddl.Items[j].Selected)
{
continue;
}
}
selected = ddl.SelectedItem.Value;
switch (selected)
{
case LIKE: // "Yes"
likesFrank = true;
break;
case DONT_LIKE: // "No"
likesFrank = false;
break;
default: // If nothing is selected in the drop-down list, move on.
continue;
} // end switch block
/* USE THE DERIVED BOOLS HERE */
} // end for loop on grid rows
} // end method cmdUpdateClick
The problem is this: No matter what item is selected in any of the dropdownlists, my page thinks that every single one of them is set to "Frank", i.e. the first item. Moreover, if I put a breakpoint on the top of the for loop denoted as the "Investigation code", and then interact with the page as follows:
Select different dropdownlist options for different rows.
Click the Update button.
... my debugging code tells me that none of the items are selected! Not one of them!! I can be looking at 2 Yes's and 3 No's on the page, and my debug tools in VS2008 are telling me that every single dropdownlist has nothing selected.
How can this be possible? (NOTE: I have tried this with EnableViewState set to true, and with EnableViewState not even mentioned in the page header.)
Thanks.
take a hit with this. Replace index based for with this
foreach(GridViewRow row in grid.Rows)
{
var ddlVal = ((DropDownList)row.FindControl("yourId")).SelectedItem.Value;
}
<< use SelectedItem.Value - I think this will solve your problem >>
Update:
To update the selected index of the ddl you needto do a postback. Enable autopostback=true. But here , you have mentioned you do not want autopostback, since this isthe only workaround, so place the gridview in an updatepanel to suppress postback
At server side
protected void btnSaveRankChanges_Click(object sender, EventArgs e)
{
foreach (GridViewRow grv in GridViewRankChanges.Rows)
{
DropDownList dropDownChangeRank = (DropDownList)grv.FindControl("DropDownListRank");
StudentInfoObject.RankID = Convert.ToInt32(dropDownChangeRank.SelectedValue);
}
}
in grid
<asp:TemplateField HeaderText="Select New Rank">
<ItemTemplate>
<asp:DropDownList ID="DropDownListRank" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
On button click
<asp:Button ID="btnSaveRankChanges" runat="server" Text="Submit" ValidationGroup="RankChanges"
class="accordionHeader" Height="27px" OnClick="btnSaveRankChanges_Click" OnClientClick="LoadImage()" />
Dropdown binds in this way
/// <summary>
/// bind dropdown with rank in grid
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridViewRankChanges_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList drdList;
// Nested DropDownList Control reference is passed to the DrdList object. This will allow you access the properties of dropdownlist placed inside the GridView Template column.
if (e.Row.RowType == DataControlRowType.DataRow)
{
//bind dropdown rank
drdList = (DropDownList)e.Row.FindControl("DropDownListRank");
drdList.DataSource = RankList.GetRankList(false);
drdList.DataTextField = "Rank";
drdList.DataValueField = "RankID";
drdList.DataBind();
drdList.Items.Insert(0, new ListItem("Select", "0"));
}
}
It works for me hope it helps for you too.
I think you are rebinding the grid on every post back, which will reload the entire data along with dropdowns. For ex. Please check if(!page.IsPostBack) before doing databiniding of gridview.
Please let me know if this is not the issue.