I have this checkboxlist that it's items fills with linq datasource now I want to check some of these check boxes programmatically...
this is my checkboxlist:
<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataSourceID="LinqDataSource2" DataTextField="ProjectGroupTitle" DataValueField="ProjectGroupID"></asp:CheckBoxList>
and this is my code trying to check some of these check boxes so far:
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Text == j.ProjectGroupTitle)
{
CheckBoxList1.Items[i].Selected = true;
}
}
when I checked this piece of code in debug mode I realized that CheckBoxList1.Items.Count value is 0 which is odd as I have multiple value in my database that linq datasource is responsible for fetching them for checkboxlist...
could someone help me fix this code?
Check the Request.Form variables while debugging. And please provide as with more information. (is it an aspx or an ascx code behind. is there any update Panel ...)
try to test your code in page render:-
<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataSourceID="LinqDataSource2" DataTextField="ProjectGroupTitle" DataValueField="ProjectGroupID" OnDataBound="SelectCheckbox"></asp:CheckBoxList>
public void SelectCheckbox(object sender, EventArgs e)
{
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Text == j.ProjectGroupTitle)
{
CheckBoxList1.Items[i].Selected = true;
}
}
}
Related
I have a simple checkbox list and I'm using a for statement to retrieve the selected values into one string. This has to be simple, but everything is returning false when it evaluates if it is selected.
ASP Code
<asp:CheckBoxList runat="server" ID="ckblInterests" ClientIDMode="Static" RepeatColumns="2" />
ASP.NET Code:
string interests = "";
for (int i = 0; i < ckblInterests.Items.Count; i++)
{
if (ckblInterests.Items[i].Selected)
{
interests += ckblInterests.Items[i].Value + ", ";
}
}
}
The inside if statement evaluates as false each time it loops through. It does count 10 items in the list correctly. I'm stumped at something so simple. Can someone help me identify what might be causing the if statement to return false?
You have code that's dynamically adding the checkboxes to the list on page load (or some other event). This is resulting in the state of those checkboxes being cleared and re-added on each postback. Your page load should probably have an if(!page.ispostback) around that section so that you aren't clearing the content.
With the Following Code (Mostly yours)
Aspx
<div>
<asp:CheckBoxList runat="server" ID="ckblInterests" ClientIDMode="Static" RepeatColumns="2">
<asp:ListItem>Awesome</asp:ListItem>
<asp:ListItem>Tasty</asp:ListItem>
<asp:ListItem>Terrible</asp:ListItem>
</asp:CheckBoxList>
</div>
<asp:Button runat="server" ID="test" OnClick="test_Click" />
<asp:Label runat="server" ID="label"></asp:Label>
c#
protected void test_Click(object sender, EventArgs e)
{
string interests = "";
for (int i = 0; i < ckblInterests.Items.Count; i++)
{
if (ckblInterests.Items[i].Selected)
{
interests += ckblInterests.Items[i].Value + ", ";
}
}
this.label.Text = interests;
}
I was able to produce the following. This is of course after clicking the button.
Are you binding to a datasource that you have not mentioned?
make sure while binding the checkboxlist in page load you have set this check if (!Page.IsPostBack) { ...bind your data }
this should do the trick
I think you need to check the CHECKED property, not SELECTED.
I have a RadGrid that I supply with data using DataSourceID. The RadGrid has paging, and I want to show the page containing some particular item. To do this, I find the offset of the item in the data and set the page number:
var index = dataSource.Count(t => t.Id > _selectedTickId);
var page = index / rgTicks.PageSize;
rgTicks.CurrentPageIndex = page;
My question is where to put this code. In the OnDataBound I don't seem to have access to the data source. If I put it in the OnSelecting the retrieving of data has a side effect of setting the page number. Should I extend the GridTableView to implement this functionality? Which method should I override?
I will suggest to compute index value in OnSelecting (which is data dependent) while page index can be set in OnDataBound or PreRender event.
My usecase was to jump to an item that was just inserted using a popup editor. Here's how I solved it. I am omitting non relevant properties in the tag. All the data wiring is up to you, but here are the relevant bits. Important: use DataKeyNames to avoid messy digging in the GridDataItem for a value.
In the page I have:
<telerik:RadGrid ID="rgItems" runat="server" AllowPaging="true"
OnNeedDataSource="rgItems_NeedDataSource"
OnPreRender="rgItems_PreRender"
OnInsertCommand="rgItems_InsertCommand">
<MasterTableView
CommandItemDisplay="Top"
CommandItemSettings-AddNewRecordText="Add New Item"
CommandItemSettings-ShowAddNewRecordButton="True"
DataKeyNames="IntItemId"
EditMode="popup"
EditFormSettings-PopUpSettings-Modal="true">
And in code behind:
private bool itemInserted = false;
protected void rgItems_InsertCommand(object sender, GridCommandEventArgs e)
{
itemInserted = true;
}
protected void rgItems_PreRender(object sender, EventArgs e)
{
if (itemInserted)
{
// Select the record and set the page
int LastItem = 0; // Put code to get last inserted item here
int Pagecount = rgItems.MasterTableView.PageCount;
int i = 0;
GridDataItem GDI = null;
while (i < Pagecount)
{
rgItems.CurrentPageIndex = i;
rgItems.Rebind();
GDI = rgItems.MasterTableView.FindItemByKeyValue("IntItemId", LastItem);
if (GDI != null) break; // IMPORTANT: Breaking here if the item is found stops you on the page the item is on
i++;
}
if (GDI != null) GDI.Selected = true; // Optional: Select the item
itemInserted = false;
}
}
I'm using C#, Asp.Net 4.0 and Telerik and I'm trying to interact with a RadComboBox.
I'm populating it with an entity data source like this :
<RadComboBox ID="cbMyCombo" runat="server" AutoPostBack="true" CheckBoxes="true" DataSourceID="edsMySource" DataTextField="Name" DataValueField="Number">
Now, it's populated properly from the database but all my items are unchecked... I tried unsuccessfully to check them by adding the following property "CheckBoxes=true" but it's not working...
I tried to change it in the code behind like this :
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
for (int i = 0; i < cbMyCombo.Items.Count; i++)
{
cbMyCombo.Items[i].Checked = true;
}
}
}
Nice try, no cigar...
I have the feeling that I'm doing it at the wrong moment in the page life cycle but I don't know how to make it properly...
Try this
Add an OnItemDataBound event to your RadCombobox
like this
protected void RadComboBox1_ItemDataBound(object o, RadComboBoxItemEventArgs e)
{
e.Item.Checked = true;
}
There is another way to handle this scenario. If all you want is - all the items in the combo box to be checked - then you can do so on the client side too. RadControls have rich client side API support so you can play around with the control from client side itself.
I tried a samll example to illustrate this scenario. I have the following radcomboboix defined on the page:
<telerik:RadComboBox runat="server" CheckBoxes="true" OnClientLoad="clientLoadHandler"
ID="radCombo"></telerik:RadComboBox>
I have named the combobox, set the CheckBoxes to true and I have added a client side event handler OnClientLoad. In this example i am binding the data source from the server as below:
List<string> colors = new List<string>
{
"Violet",
"Indigo",
"Blue",
"Green",
"Yellow",
"Orange",
"Red"
};
radCombo.DataSource = colors;
radCombo.DataBind();
Here is the javascript function:
function clientLoadHandler(sender) {
var combo = sender;
var items = combo.get_items();
var itemCount = items.get_count()
for (var counter = 0; counter < itemCount; counter++) {
var item = items.getItem(counter);
item.set_checked(true)
}
}
As you can see, the sender parameter of the function is the combobox. I gets items out of the combobox and loop through each item and set its checked property using the set_checked(boolean) function.
hope you find this info useful. Do let me know what you think about this solution.
Lohith (Tech Evangelist, Telerik India)
I have a ListView control. I am displaying the data but once the user clicks the clear button
all the data that is shown in the ListView control should go off (empty). We should clear it contents and display a message no data to be displayed.
Even the paging (I am using DataPager control to achive paging) which was shown earlier when data was there should not be shown as we have cleared the data. My code looks like this:
protected void lvEmployee_DataBound(object sender, EventArgs e)
{
DropDownList ddl = DataPager1.Controls[1].FindControl("ddlPage") as DropDownList;
int PageCount = (DataPager1.TotalRowCount / DataPager1.PageSize);
if (PageCount*DataPager1.PageSize != DataPager1.TotalRowCount)
{
PageCount = PageCount + 1;
}
for (int i = 0; i < PageCount; i++)
{
ddl.Items.Add(new ListItem((i+1).ToString(),i.ToString()));
}
ddl.Items.FindByValue(CurrentPage.ToString()).Selected = true;
}
When I clear, all the data should go off and even the paging.
To clear all the values:
// in your .cs
lvEmployee.DataSource = null;
lvEmployee.DataBind();
To display a message when no data exists implement the EmptyDataTemplate:
// in your .aspx
<asp:ListView ID="lvEmployee" runat="server">
<EmptyDataTemplate>
No data available.
</EmptyDataTemplate>
</asp:ListView>
I'm working on creating a dynamic list of checklists and came to the below implementation. I have been trying for a week now to get the fnameID text values on the submit button click to send the values into the database. I do not want to use the postback oncheckedchanged.on each check because the checklist is over 1000 rows long and each postback/reload wastes too many resources. I just want to be able to use some method to be able to grab the checked values so I can insert them into the database on the submit button "Click Me!" click.
I googled and found the FindControl method but i still am not able to grab the fnameID values. I either get a undefined or it errors out on me. Any help would be greatly appreciated! Thanks!
aspx:
<div id="aGAccountabilityCheckListBox">
"Panel1" runat="server">
<asp:LinkButton ID="LinkButton1" Width="66px" runat="server" onclick="LinkButton1_Click">
Click Me!
</asp:LinkButton>
code behind:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
Panel1.Controls.Add(_checkbox);
Panel1.Controls.Add(" <span id='fnameID" + i + "' >test" + i + "</span>");
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["cnDatabase"].ToString());
SqlCommand cmd = new SqlCommand("usp_CreateUser", cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
Thanks!
State is restored to controls before the load event runs. If your controls don't already exist by then, they'll lose their state and you won't know they were checked. Create your checkboxes in the Init or PreInit event instead.
move the checkbox creation to the CreateChildControls page method
to retrieve checkbox state in the LinkButton1_Click handler you can use the following code
for (int i = 0; i < 50; i++)
{
string cbxId = string.Format("dynamicCheckListBox{0}", i);
CheckBox _checkbox = Panel1.FindControl(cbxId) as CheckBox;
if (_checkbox == null )
continue;
if ( _checkbox.Checked )
//do something
}
Your fnameID's are spans created as a literal control. There is no post back value you are going to get if you set it up that way. It's just arbitrary html or text from the asp.net perspective.
Why are you not using the Text property for CheckBox?