CheckBox on a GridView - asp.net

I have a grid view that has 3 columns(Name, Address, Status) and a checkbox.The Status has 3 properties, Active, Pending, and Disabled. The page load all the information from the database. When loading the page, only accounts that are ACTIVE should be displayed (and the checkbox should remain unchecked)
When clicking the checkbox, the page should load the DISABLED, along with the accounts already displayed When the page loads for the first time.
Aspx:
<asp:CheckBox ID="ChkBox1" runat="server" AutoPostBack="true" OnCheckedChanged="cbShowAllColumn_Changed" TextAlign="Right" Text="Show All"/>
</asp:Panel>
Code behind:
protected void cbShowColumn_Changed(object sender, EventArgs e)
{
string columnName = (sender as CheckBox).ID.Substring(1);
gvTest.Columns[(int)Enum.Parse(typeof(AccountColumns), columnName)].Visible = (sender as CheckBox).Checked;
}
protected void cbShowAllColumn_Changed(object sender, EventArgs e)
{
bool _checked = (sender as CheckBox).Checked;
foreach (Control ctrl in pAccount.Controls)
if (ctrl is CheckBox)
{
(ctrl as CheckBox).Checked = _checked;
gvMain.Columns[(int)Enum.Parse(typeof(AccountColumns), (ctrl as CheckBox).ID.Substring(2))].Visible = _checked;
}
}

I compiled a small asp .net page to do what you asked.
Note: In your project, you should probably take the "source" out of the BindGrid method, so that you don't "get" the data from scratch every time the page is posted back to. I did it that way because I used an anonymous type.
Note #2 I converted an int to your enum and then to a string. Since you use real data you should handle that differently, by using the enum itself.
Markup:
<asp:CheckBox ID="ChkBox1" runat="server" AutoPostBack="true" OnCheckedChanged="cbShowAllColumn_Changed" TextAlign="Right" Text="Show All"/>
<br/>
<asp:gridview ID="gvMain" runat="server" >
</asp:gridview>
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
BindGrid(false);
}
private void BindGrid(bool showActiveOnly)
{
var source = Enumerable.Range(1, 10)
.Select(number => new { number, status = (Enum.ToObject(typeof(Statuses), number % 3)).ToString() });
var filteredSource = source.Where(x => x.status == "Active" || !showActiveOnly);
gvMain.DataSource = filteredSource;
gvMain.DataBind();
}
protected void cbShowAllColumn_Changed(object sender, EventArgs e)
{
bool _checked = (sender as CheckBox).Checked;
BindGrid(_checked);
}
private enum Statuses
{
Active,
Pending,
Disabled
}

Related

Repeater with dynamic UC

I have a formular with dynamic data and UC.
my ascx file looks like:
<asp:Repeater ID="rMyData" runat="server" OnItemDataBound="OnRepeaterItemDataBound">
<ItemTemplate>
<asp:Panel ID="panelAdditional" runat="server"/>
</ItemTemplate>
</asp:Repeater>
and the cs file:
public partial class MyFormular
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PrepareList();
DataBind();
}
}
private void PrepareList()
{
rMyData.DataSource = GetData();
rMyData.DataBind();
}
protected void OnRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem repeaterItem = e.Item;
Panel panel = (Panel)repeaterItem.FindControl("panelAdditional");
if (panel != null)
{
var datarow= (Data)repeaterItem.DataItem;
if (datarow!= null)
{
panel.Controls.Clear();
MyUC ctrl;
ctrl = (MyUC)Page.LoadControl("~/MyUC.ascx");
ctrl.Enabled = true;
ctrl.DataRow = datarow;
panel.Controls.Add(ctrl);
}
}
}
protected void SaveNewsletterSubscription(object sender, EventArgs e)
{
...
}
}
My problem is, it doesn't show my UC.
If I put my PrepareList() and DataBind() outside of the PostBack, it works perfectly fine and shows my UC. But after I press the save Button, it reloads the page and rebind my repeater. So I lost everything in the UC.
Why does it only show my UC if I rebind it in every pageload?
I hope the I posted enough information.

Implementing search page

I'm new to ASP.Net and trying to implement a search page in my project.
I created a simple search.aspx
<asp:TextBox runat="server" ID="txtSearch" MaxLength="250"/>
<asp:LinkButton ID="lnkSearch" runat="server" Text="Search" OnClick="Search_Click" ClientIDMode="Static" />
<asp:Repeater ID="rep" runat="server" >
....
</asp:Repeater>
and the search.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
txtSearch.Text = Request.Params["q"].ToString();
BindRepeater(); //reads Request.Params["q"] and fetches data
txtSearch.Focus();
this.Page.Form.DefaultButton = this.lnkSearch.UniqueID;
}
protected void Search_Click(object sender, EventArgs e)
{
Response.Redirect("/Search.aspx?q=" + txtSearch.Text);
}
Problem is that when I type something in txtSearch and hit enter or click search, the page reloads with the old query string and old search results, seems that txtSearch.Text is updated with old Query value before hitting Search_Click
For Example if I enter search.aspx?q=apple in address bar the page returns correct results and txtSearch's Text = "apple" .. if I type green apple and hit enter, page returns apple results, and txtSearch's Text = "apple", also the link is search.aspx?q=apple
I tried
AutoPostBack="True|False" for the TextBox
if (!IsPostBack)
txtSearch.Text = Request.Params["q"].ToString();
but I can't use it I guess since I'm posting back to same page, no?
I also tried
if (IsPostBack && txtSearch.Text != Request.Params["q"].ToString())
txtSearch.Text = Request.Params["q"].ToString();
This seems a strange way of doing it to me.
My preference would be to have the search logic in the event handler itself, rather than implementing this strange post-back loop.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
// If passed in on first entry to the page
var searchQuery = Reqest.Params["q"];
if (String.IsNullOrWhitespace(searchQuery) == false)
{
txtSearch.Text = searchQuery;
Search_Click(null, null);
}
}
txtSearch.Focus();
this.Page.Form.DefaultButton = this.lnkSearch.UniqueID;
}
protected void Search_Click(object sender, EventArgs e)
{
// Pass the value of the search to the repeater
BindRepeater(txtSearch.Text);
}
Note that I'm passing the search text to BindRepeater so you'd have to update it to use the parameter value rather than query string

Radio button doesn't get selected after a post back

I have an item template within repeater:
<ItemTemplate>
<li>
<input type="radio"
value="<%# GetAssetId((Guid) (Container.DataItem)) %>"
name="AssetId"
<%# SelectAsset((Guid) Container.DataItem) %> />
</li>
</ItemTemplate>
I have a method that compares ids and decides whether to check the radio button.
protected string SelectAsset(Guid uniqueId)
{
if (uniqueId == GetSomeId())
return "checked=\"checked\"";
return string.Empty;
}
SelectAsset gets hit, but it doesn't select a radio button on a post back, but it does work if I just refresh the page. What am I doing wrong here?
Answer here: How to display "selected radio button" after refresh? says that it's not possible to achieve, is this really the case?
Thank you
Update
It appears that view state isn't available for simple controls if they don't have a runat attribute. I have solved this by using a custom GroupRadioButton control. Thank you for your help.
I'd suggest using a RadioButtonList:
Page Code
<asp:RadioButtonList RepeatLayout="UnorderedList" OnSelectedIndexChanged="IndexChanged" AutoPostBack="true" ID="RadioRepeater" runat="server" />
<asp:Label ID="SelectedRadioLabel" runat="server" />
Code Behind
if (!Page.IsPostBack)
{
/* example adds items manually
- you could iterate your datasource here as well */
this.RadioRepeater.Items.Add(new ListItem("Foo"));
this.RadioRepeater.Items.Add(new ListItem("Bar"));
this.RadioRepeater.Items.Add(new ListItem("Baz"));
this.RadioRepeater.SelectedIndex = this.RadioRepeater.Items.IndexOf(new ListItem("Bar"));
this.RadioRepeater.DataBind();
}
protected void IndexChanged(object sender, EventArgs e)
{
this.SelectedRadioLabel.Text = string.Format("Selected Item Text: {0}", this.RadioRepeater.SelectedItem.Text);
}
I assume you only need to select one item.
As described in the comments, it even works to access the SelectedItem in the Page_Loadevent handler:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// previous code omitted
}
else
{
string foo = this.RadioRepeater.SelectedItem.Text;
}
}
If you are creating all your controls dynamically at run-time (directly from code), then things are a little different. Here is the code that I used:
Page Code
<form id="form1" runat="server">
</form>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
RadioButtonList rbl = new RadioButtonList();
rbl.AutoPostBack = true;
rbl.SelectedIndexChanged += rbl_SelectedIndexChanged;
rbl.Items.Add("All");
// generate your dynamic radio buttons here
for (int i = 0; i<5; i++)
{
rbl.Items.Add(string.Format("Dynamic{0}", i));
}
form1.Controls.Add(rbl);
if (!Page.IsPostBack)
{
rbl.SelectedValue = "All";
PopulateTextBox(rbl.SelectedValue);
}
}
void rbl_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList foo = (RadioButtonList)sender;
PopulateTextBox(foo.SelectedValue);
}
void PopulateTextBox(string selection)
{
TextBox box = new TextBox();
box.Text = selection;
form1.Controls.Add(box);
}

Paging ObjectDataSource

My ASP page code:
<asp:ObjectDataSource runat="server" ID="odsResults" OnSelecting="odsResults_Selecting" />
<tr><td>
<wssawc:SPGridViewPager ID="sgvpPagerTop" runat="server" GridViewId="sgvConversionResults" />
</td></tr>
<tr>
<td colspan="2" class="ms-vb">
<wssawc:SPGridView
runat="server"
ID="sgvConversionResults"
AutoGenerateColumns="false"
RowStyle-CssClass=""
AlternatingRowStyle-CssClass="ms-alternating"
/>
</td>
</tr>
Class code:
public partial class Convert : System.Web.UI.Page
{
...
private DataTable resultDataSource = new DataTable();
...
protected void Page_Init(object sender, EventArgs e)
{
...
resultDataSource.Columns.Add("Column1");
resultDataSource.Columns.Add("Column2");
resultDataSource.Columns.Add("Column3");
resultDataSource.Columns.Add("Column4");
...
odsResults.TypeName = GetType().AssemblyQualifiedName;
odsResults.SelectMethod = "SelectData";
odsResults.SelectCountMethod = "GetRecordCount";
odsResults.EnablePaging = true;
sgvConversionResults.DataSourceID = odsResults.ID;
ConversionResultsCreateColumns();
sgvConversionResults.AllowPaging = true;
...
}
protected void btnBTN_Click(object sender, EventArgs e)
{
// add rows into resultDataSource
}
public DataTable SelectData(DataTable ds,int startRowIndex,int maximumRows)
{
DataTable dt = new DataTable();
dt.Columns.Add("Column1");
dt.Columns.Add("Column2");
dt.Columns.Add("Column3");
dt.Columns.Add("Column4");
for (int i =startRowIndex; i<startRowIndex+10 ;i++)
{
if (i<ds.Rows.Count)
{
dt.Rows.Add(ds.Rows[i][0].ToString(), ds.Rows[i][1].ToString(),
ds.Rows[i][2].ToString(), ds.Rows[i][3].ToString());
}
}
return dt;
}
public int GetRecordCount(DataTable ds)
{
return ds.Rows.Count;
}
protected void odsResults_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["ds"] = resultDataSource;
}
}
On clicking the button resultDataSource receives some rows. Page reload and we can see result in sgvConversionResults. First 10 rows. But after click next page in pager we have message "There are no items to show in this view". When I try debug I find that after postBack page (on click next page) input params "ds" is blank, ds.Rows.Count = 0 and etc... As though resultDataSource became empty((
What did I do incorrectly?
onPostBack all variables get default values, sgvConversionResults save her structure but has clear rows. How I can save sgvConversionResults data onPostBack event???
Maybe try:
protected void Page_Load(object sender, EventArgs e)
{
sgvConversionResults.DataBind();
}
Your code seems a bit convoluted though, any particular reason you are using an ObjectDataSource? Cause you can bind the datatable directly to the gridview in the codebehind
I transmit resultDataSource with ViewState and this work success!

ListBox retains posted value even after being databound

Please note that the problem described below is almost the exact opposite to the common problem of "my control shows the same value every time the page loads. I understand the behavior expressed is generally not desirable.
I have a listbox which is being databound in the page load event even on postback.
When the event handler for the selectedindex changed is hit, the control somehow has the posted value even though it has already been bound again and should not have a selectedindex at this point.
Does anyone know how this could be possible.
EDIT:
To demonstrate that the SelectedIndex is indeed reset you can create a form with the following simple markup:
<label for="textbox1">Original Posted Value: </label>
<asp:TextBox runat="server" ID="textbox1" />
<asp:DropDownList runat="server" ID="dropdown" OnSelectedIndexChanged="dropdown_SelectedIndexChanged" AutoPostBack="true" />
<label for="textbox2">Value at point handler is hit: </label>
<asp:TextBox runat="server" ID="textbox2" />
With the following code in the .cs
protected void Page_Load(object sender, EventArgs e)
{
textbox1.Text = dropdown.SelectedIndex.ToString();
dropdown.DataSource = new string[] { "none", "A", "B", "C" };
dropdown.DataBind();
}
protected void dropdown_SelectedIndexChanged(object sender, EventArgs e)
{
textbox2.Text = dropdown.SelectedIndex.ToString();
}
Notice that the value in the second textbox will alway be 0.
The problem here is that the datasource is getting re-assigned and re-bound on each page load including postbacks. The selected index is changed and then changed back to 0.
Try cathcing the postbacks, and only set the datasource if it is not a postback (the initial load) such as this in the .cs
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
textbox1.Text = dropdown.SelectedIndex.ToString();
}
else
{
dropdown.DataSource = new string[] { "none", "A", "B", "C" };
dropdown.DataBind();
}
}
protected void dropdown_SelectedIndexChanged(object sender, EventArgs e)
{
textbox2.Text = dropdown.SelectedIndex.ToString();
}

Resources