how to manipulate list of selected values in checkbox - C# - c#

I have set up the following method for multiple selection from user and store it in CSV format in Database.
<div class="col-md-10" style="padding-top: 7px;">
<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataTextField="language" DataValueField="language" AutoPostBack="True" RepeatLayout="OrderedList" Width="432px">
<asp:ListItem Value="Saturday">Saturday</asp:ListItem>
<asp:ListItem Value="Sunday">Sunday</asp:ListItem>
<asp:ListItem Value="Monday">Monday</asp:ListItem>
<asp:ListItem Value="Tuesday">Tuesday</asp:ListItem>
<asp:ListItem Value="Wednesday">Wednesday</asp:ListItem>
<asp:ListItem Value="Thursday">Thursday</asp:ListItem>
</asp:CheckBoxList>
</div>
private string CheckBoxListDataToCSV()
{
string selectedItems = String.Join(",",
CheckBoxList1.Items.OfType<ListItem>().Where(r => r.Selected)
Select(r => r.Text));
return selectedItems;
}
string str = CheckBoxListDataToCSV(); //This method to Add in datarow
My question is that how to populate back the values in their check boxes when Add/Edit activity perform.
Thanking in Advance

return dataset containing csv then
DataTable dt = dsPage.Tables[0];
string strArr = dt.Rows[0]["Training_Days"].ToString();
string[] Arr = strArr.Split(',');
for (int j = 0; j < Arr.Length; j++)
{
for (int i = 0; i < Arr.Length; i++)
{
if (CheckBoxList1.Items.FindByText(Arr[i]) != null)
{
CheckBoxList1.Items.FindByText(Arr[i]).Selected = true;
continue;
}
}
}

Related

for loop in c# for IDs of controls to read text of textbox

<asp:TextBox ID="PFtxtname1" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname2" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname3" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname4" runat="server"></asp:TextBox>
<asp:TextBox ID="PFtxtname5" runat="server"></asp:TextBox>
.
.
.
<asp:TextBox ID="PFtxtname100" runat="server"></asp:TextBox>
I need to create for loop to read all data of txt and save all in string array variable!
//string[] arr = new string[100];
// for (int i = 0; i < 100; i++)
// {
//arr[i] = (i+1).ToString();
//i+=1;
//TextBox mytext = new TextBox();
//mytext.ID = "PFtxtname" + i;
//TextBox txtbox = Page.FindControl("PFtxtname"+i) as TextBox;
//i += 1;
//arr[i] = txtbox.Text;
//}
In the future, please provide any detail and data that can help us help you. Also, do appropriate research prior to posting. There are MANY different ways to do this, and it can differ between ASP.NET frameworks (forms/mvc/razor/etc); many of which have questions already asked and answered on stackoverflow.
In any case this should at least get you started. LINQ is your friend! (may need to add using)
var listOfText = new List<string>();
foreach (var textbox in this.Controls.OfType<TextBox>())
{
listOfText.Add(textbox.Text);
}
you can try this
//Member variable
var textBox = new TextBox();
public void CreateTextBox(int length)
{
for (int index = 0; index < length; index++)
{
textBox = new TextBox();
textBox.ID = "PFtxtname" + "_" + index;
textBox.CssClass = "yourCSSClass";
textBox.ClientIDMode = ClientIDMode.Static;
this.Controls.Add(textBox);
}
}
get the textbox values bt calling getTextBoxValues method
public string[] getTextBoxValues(int length)
{
string[] arr = new string[length];
for (int index = 0; index < length; index++)
{
TextBox txtbox = Page.FindControl("PFtxtname_"+ index) as TextBox;
arr[nRowIndex] = txtbox.value;
}
return arr;
}

How to control page numbers in pagination?

I have written below lines of code
public void UpdatePageLables(int aPageCount)
{
PageCount = (int)Math.Ceiling((decimal)aPageCount / PageSize);
int recordCount = PageCount;
if (PageSizeChanged != null)
{
HiddenField hd = new HiddenField();
int current;
current = PageIndex;
int pre;
int Next;
double dblPageCount = (double)((decimal)recordCount / decimal.Parse(lstPageSize.SelectedValue));
int pageCount = PageCount;
List<ListItem> pages = new List<ListItem>();
if (pageCount > 0)
{
// pages.Add(new ListItem("First", "1", PageIndex > 1));
current = PageIndex;
pre = --PageIndex;
PageIndex = current;
// pages.Add(new ListItem("Previous", pre.ToString(), PageIndex > 1));
for (int i = 1; i <= aPageCount; i++)
{
pages.Add(new ListItem(i.ToString(), i.ToString(), i != PageIndex));
}
int currentPage = PageIndex;
Next = ++PageIndex;
PageIndex = currentPage;
//pages.Add(new ListItem("Next", Next.ToString(), PageIndex < pageCount));
// pages.Add(new ListItem("Last", pageCount.ToString(), PageIndex < pageCount));
hd.Value = (pre.ToString());
}
rptPager.DataSource = pages;
rptPager.DataBind();
}
}
And in ascx file
<div class="pagination">
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" OnClick="imgPre_Click"
data-rel="tooltip" data-original-title="previous page.">«</asp:LinkButton>
<asp:Repeater ID="rptPager" OnItemDataBound="rptPager_ItemDataBound" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lnkPage" runat="server" Text = '<%#Eval("Text") %>' CommandArgument = '<%# Eval("Value") %>' Enabled = '<%# Eval("Enabled") %>' OnClick = "Page_Changed"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="false" OnClick="imgnext_Click"
data-rel="tooltip" data-original-title="next page."> »
</asp:LinkButton>
<div class="page-size"><span>Page Size: </span>
<asp:DropDownList runat="server" ID="lstPageSize" AutoPostBack="true" style="float:right"
OnSelectedIndexChanged="lstPageSize_SelectedIndexChanged">
<asp:ListItem Text="5" Value="5"></asp:ListItem>
<asp:ListItem Text="10" Value="10"></asp:ListItem>
<asp:ListItem Text="15" Value="15" Selected="True"></asp:ListItem>
<asp:ListItem Text="25" Value="25" ></asp:ListItem>
<asp:ListItem Text="50" Value="50"></asp:ListItem>
<asp:ListItem Text="75" Value="75"></asp:ListItem>
<asp:ListItem Text="100" Value="100"></asp:ListItem>
<asp:ListItem Text="150" Value="150"></asp:ListItem>
</asp:DropDownList>
</div>
</div>
Now I want to display only first seven page number links when there will be hundred page number links and rest of page number links should not be displayed.
When user will click on ... button then page numbers from 8 to 14 should get displayed and 1 to 7 should be hidden and so on.
Please help me !!!
You should only fill your list of pages with the pages you want. So if you want 7 pages (3 left to selected index and 3 right to selected index) you can do:
for (int i = PageIndex - 3; i <= PageIndex + 3; i++)
{
if (i > 0 && i <= aPageCount) {
{
//i is still inside total range of pages, so page can be added
pages.Add(new ListItem(i.ToString(), i.ToString(), i != PageIndex));
}
}
If you want other list of pages (like 7 next after PageIndex) you need to change the for loop.

Im trying to create an ASP.NET table using a for loop for a set of hyperlinks

I have list of hyperlinks which i want to use to create a 2x* table (* is number of hyperlinks)
Here is my code...
for (int rows = 0; rows < hlist.Count; rows++) //Create rows for the number of hyperlinks, so i will always have a spare row.
{
TableRow row = new TableRow(); // Create the new rows
table.Rows.Add(row); //Add rows to the table
for (int cells = 0; cells < 2; cells++)
{
TableCell cell = new TableCell();
for(int h = 0; h < hlist.Count; h++)
cell.Controls.Add(hlist[h]);
row.Cells.Add(cell);
}
}
All this does is list all my hyperlinks in a single column table, with a new row for each hyperlink!
Any help would be appreciated!!
Thanks
Assuming that you want to create a table that shows two hyperlinks per row, you could try the following code:
for (int i = 0; i < hlist.Count; i += 2)
{
TableRow row = new TableRow(); // Create the new rows
table.Rows.Add(row);
for (int j = i; j < Math.Min(i + 2, hlist.Count); j++)
{
TableCell cell = new TableCell();
cell.Controls.Add(hlist[j]);
row.Controls.Add(cell);
}
}
However, using dynamically added controls in ASP.NET is complex if you want them to react on events. So I'd propose to check whether you could change your approach so that you can use a Repeater instead. In order to do so, you'd first have to change your data model, e.g. to a list of Pair objects that contain two URLs, e.g.:
public void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
IEnumerable<Uri> uris = GetUris();
List<Tuple<Uri, Uri>> pairs = new List<Tuple<Uri, Uri>>();
for (int i = 0; i < uris.Count; i += 2)
{
var uri1 = uris[i];
var uri2 = i + 1 < uris.Count ? uris[i + 1] : null;
pairs.Add(new Tuple<Uri, Uri>(uri1, uri2));
}
rpt.DataSource = pairs;
rpt.DataBind();
}
}
If your URLs are not compatible with a Uri (maybe they contain a leading ~), you can also use strings instead of Uri.
The markup for your the Repeater would look similar to this:
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:HyperLink runat="server" Text="Link 1"
NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "Item1") %>' />
</td>
<td>
<asp:HyperLink runat="server" Text="Link 1"
NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "Item2") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

Using the selected value of a dropdown list in an if statement

I'm trying to select the value from this drop down list to use in an if statement so that I can then do calculations based on which choice is chosen. I'm not sure if this is the right way to do it, any help would be much appreciated!
<asp:DropDownList ID="ddlHours" runat="server">
<asp:ListItem >Select</asp:ListItem>
<asp:ListItem >Part-Time</asp:ListItem>
<asp:ListItem >Full-Time</asp:ListItem>
</asp:DropDownList>
const int PART_TIME = 15;
const int FULL_TIME = 25;
double fee = 0;
if (ddlHours.SelectedItem.Value == "Part-Time")
{
CalculatePartTime(PART_TIME, fee);
}
else if (ddlHours.SelectedItem.Value == "Full-Time")
{
CalculateFullTime(FULL_TIME, fee);
}
lblAnswer.Text = String.Format("{0}",fee);
I would use :
if (ddlHours.SelectedItem.Text == "Part-Time")
it looks like you are not looking for value you are looking for text
if(ddlHours.SelectedItem.Text == "Part-Time")
if you open to javascript/jquery, you could do this:
var PART_Time = 15;
var FULL_TIME = 25;
var fee = 0;
$('#ddlHours').change(function() {
var $this = $(this);
if ($this.val() == 'Part-Time') {
$('#labelAnswer').val(CalculatePartTime(PART_TIME, fee);
}
else {
$('#labelAnswer').val(CalculateFullTime(FULL_TIME, fee);
}
});
i know this doesn't answer your specific question but this would reduce postbacks.

Changing selection for a DropdownList triggers OnSelectedIndexChanged event of a CheckBoxList

Basically I want to implement a filtering option for a Grid view and I have a dropdown list containing the column names and a checkboxlist containing the available filtering values for that column. Every time I select a different column, I have to load the filtering values for that column into the checkbox list.
The problem I have is that when I change the column in the dropdown list, the event for the checklist is fired and the application crashes.
My controls are defined like this:
<div class="LeftAligned">
<asp:Label ID="FilterLabel" runat="server" Text="Filter by:" />
<asp:DropDownList runat="server" ID="FilterReviewsDropDownList" AutoPostBack="true" OnSelectedIndexChanged="FilterReviewsDropDownList_SelectedIndexChanged" />
<asp:ImageButton ID="FilterReviewsButton" runat="server" ImageUrl="~/images/filter.png" AlternateText="VALUE" CssClass="filter_button" OnClick="FilterReviewsButton_Click" />
<div onmouseout="javascript:bMouseOver=false;" onmouseover="javascript:bMouseOver=true;" class="filter_div">
<asp:CheckBoxList AutoPostBack="true" ID="FilterReviewsCheckBoxList" ClientIDMode="Static" runat="server" CssClass="filter_checklist collapsed"
OnSelectedIndexChanged="FilterReviewsCheckBoxList_Selected">
</asp:CheckBoxList>
</div>
<%--asp:Button runat="server" ID="ApplyFilterButton" Text="Apply Filter" OnClick="ApplyFilterButton_Click"/>
<asp:Button runat="server" ID="ClearFilterButton" Text="Clear Filter" OnClick="ClearFilterButton_Click"/--%>
</div>
In the CodeBehind file I have the following code:
protected void FilterReviewsButton_Click(object sender, EventArgs e)
{
FilterReviewsCheckBoxList.CssClass = "filter_checklist";
}
protected void FilterReviewsDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
LoadFilterCheckboxes(FilterReviewsDropDownList.SelectedIndex);
}
private void LoadFilterCheckboxes(int iColumn)
{
SortedSet<string> oItems = new SortedSet<string>();
for (int i = 0; i < ReviewsGridView.Rows.Count; i++)
{
IEnumerable<Label> oLabels = ReviewsGridView.Rows[i].Cells[iColumn].Controls.OfType<Label>();
string sValue = "";
if (oLabels != null && oLabels.Count() > 0)
{
sValue = oLabels.First().Text;
}
else
{
sValue = ReviewsGridView.Rows[i].Cells[iColumn].Text;
}
if (!oItems.Contains(sValue))
oItems.Add(sValue);
}
FilterReviewsCheckBoxList.Items.Clear();
FilterReviewsCheckBoxList.Items.Add("All");
FilterReviewsCheckBoxList.Items[0].Selected = true;
foreach (string sItem in oItems)
{
FilterReviewsCheckBoxList.Items.Add(sItem);
FilterReviewsCheckBoxList.Items[FilterReviewsCheckBoxList.Items.Count - 1].Selected = true;
}
}
protected void FilterReviewsCheckBoxList_Selected(object sender, EventArgs e)
{
string sResult = Request.Form["__EVENTTARGET"];
if (string.IsNullOrEmpty(sResult))
{
FilterReviewsCheckBoxList.Items[0].Selected = true; //weird bug fix...
return;
}
string[] sCheckedBox = sResult.Split('$');
//get the index of the item that was checked/unchecked
int i = int.Parse(sCheckedBox[sCheckedBox.Length - 1].Split('_')[1]);
if (i == 0)
{
if (FilterReviewsCheckBoxList.Items[i].Selected == true)
{
for (int j = 1; j < FilterReviewsCheckBoxList.Items.Count; j++)
FilterReviewsCheckBoxList.Items[j].Selected = true;
}
else
{
for (int j = 1; j < FilterReviewsCheckBoxList.Items.Count; j++)
FilterReviewsCheckBoxList.Items[j].Selected = false;
}
}
else
{
if (FilterReviewsCheckBoxList.Items[i].Selected == false)
{
FilterReviewsCheckBoxList.Items[0].Selected = false;
}
else
{
//if (oFirstTable != null)
//{
// oTable = oFirstTable;
// oView = oTable.DefaultView;
//}
bool bAllChecked = true;
for (int j = 1; j < FilterReviewsCheckBoxList.Items.Count; j++)
{
if (FilterReviewsCheckBoxList.Items[j].Selected == false)
{
bAllChecked = false;
break;
}
}
if (bAllChecked)
FilterReviewsCheckBoxList.Items[0].Selected = true;
}
}
}
Any idea of why FilterReviewsCheckBoxList_Selected is called (with the dropdownlist as the sender argument) when changing the dropdown list?
For anyone who may encounter the same problem, the fix is to avoid static binding of the grid view to entity data source. Instead, bind the grid dynamically in the page load event.

Categories

Resources