Radio button is not functioning - asp.net

I'm having problem with my radio button in my gridview. I want to select any row one by one so that I can perform UPDATE, DELETE, and DISPLAY the row. When I select the button, the page will be refreshed and the button I selected before is not selected anymore. So I can't click any menu to update, delete or display the row. I noticed this is happening when I set the Autopostback = "True".
How can I solve it? Any idea? Below are my codes:
Page:
<script language="javascript" type="text/javascript">
function radiobtn(id) {
var rdBtn = document.getElementById(id);
var List = document.getElementsByTagName("input");
for (i = 0; i < List.length; i++) {
if (List[i].type == "radio" && List[i].id != rdBtn.id) {
List[i].checked = false;
}
}
}
</script>
<asp:RadioButton ID="CheckDel" runat="server" onclick="javascript:radiobtn(this.id)" OnCheckedChanged="CheckDel_CheckedChanged"
AutoPostBack="True" />
server end:
protected void CheckDel_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkStatus = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkStatus.NamingContainer;
Session["datestart"] = row.Cells[1].Text;
Session["empid"] = row.Cells[2].Text;
Session["empname"] = row.Cells[3].Text;
Session["days"] = row.Cells[4].Text;
Session["leavetype"] = row.Cells[5].Text;
Session["leavestatus"] = row.Cells[6].Text;
bool status = chkStatus.Checked;
}

Do look at the following url http://www.asp.net/web-forms/tutorials/data-access/enhancing-the-gridview/adding-a-gridview-column-of-radio-buttons-cs
Look at section "Using a Literal Control to Inject Radio Button Markup" for more info

Related

How can I delete a dynamical control from an UpdatePanel at the click of a button?

I have an ASP.NET UpdatePanel where I add other panels dynamically. Each of these smaller panels has their own "Delete" Button.
When I click on one of those "Delete" button, I want the corresponding panel to be deleted. Instead, what happens is: I press "Delete", nothing happens, then when I do another operation that causes a PostBack, the panel is deleted. (Too late)
I draw every dynamical control on PostBack and when I click the Delete button, its handler (which deletes the panel I want) only occurs after I draw every control, so I don't see any changes immediately.
Here's the code that is called on every postback:
private void drawForm()
{
if (Session["controls"] != null)
{
PlaceHolder1.Controls.Clear();
Ccontrols = (Dictionary<Label, Control>)Session["controls"];
int index = 1;
foreach (var entry in Ccontrols)
{
Panel cPanel = new Panel();
cPanel.CssClass = "controldiv";
cPanel.ID = "cpanel" + index;
Button closebtn = new Button();
closebtn.Text = "Delete";
closebtn.ID = "closebtn" + index++;
closebtn.Click += new EventHandler(closeControl);
cPanel.Controls.Add(entry.Key);
cPanel.Controls.Add(entry.Value);
cPanel.Controls.Add(closebtn);
cPanel.Controls.Add(new LiteralControl("<br />"));
cPanel.Controls.Add(new LiteralControl("<br />"));
closebtn.CssClass = "closebutton";
PlaceHolder1.Controls.Add(cPanel);
}
FormPanel.Update();
}
else
{
FormPanel.ContentTemplateContainer.Controls.Clear();
}
Here is the DeleteButton handler:
private void closeControl(object sender, EventArgs e)
{
String id = (sender as Button).ID;
PlaceHolder1.Controls.Remove(PlaceHolder1.FindControl("cpanel" + id));
foreach (Control c in (sender as Button).Parent.Controls)
{
if (c is Label)
{
Ccontrols.Remove((Label)c);
}
}
Session["controls"] = Ccontrols;
drawForm();
}
Thanks in advance
I think there is some problem with your triggers in UpdatePanel.
I would be able to help you better if you would post your html code where you have created your UpdatePanel.

How to disable some checkboxes of checkboxlist based on database value in asp.net?

I have a checkboxlist which has 26 values getting filled from database.
<asp:CheckBoxList ID="chkList1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%" DataTextField="Name" DataValueField="ID" AutoPostBack="True" Visible="false" OnSelectedIndexChanged="chkList1_SelectedIndexChanged">
</asp:CheckBoxList>
public QueSet()
{
SqlConnection conn = new SqlConnection(Settings.DatabaseConnectionString);
try
{
conn.Open();
SqlCommand com = new SqlCommand("sp_SelectQueSet",conn);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sa = new SqlDataAdapter(com);
DataSet ds = new DataSet();
sa.Fill(ds);
if(ds.Tables.Count > 0)
{this.Data = ds.Tables[0];}
}
catch(Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{conn.Close();}
}
QueSet q = new QueSet();
chkList1.DataSource = q.Data;
chkList1.DataBind();
Based on above code, the checkboxlist gets data from database. One of the values from the database is "Nothing" with ID 51.
I want to disable all the other checkboxes if user selects "Nothing" value.
protected void chkList1_SelectedIndexChanged(object sender, EventArgs e)
{
//what should I do here?
}
This can be easly achived by Client Script, Server SelectedIndexChanged is not required. do the steps as follows
Remove AutoPostback = "true" and OnSelectedIndexChanged="..." from
your CheckboxList control and Add the property CssClass ="CHKList"
Attach jQuery.js , say jQuery-1.7 or latest version
Add the following code in ASPX Page. This will disable all checkboxes when anyone of check box is clicked and Enable back if unchecked
<script>
$(document).ready(function () {
$(".CHKList input:checkbox").click(function () {
if ($(this).prop("checked") == true) {
$(".CHKList input:checkbox").prop("disabled", true);//older version of jQuery prop will not work , use attr("disabled","disabled");
$(this).prop("disabled", false);
}
else {
$(".CHKList input:checkbox").prop("disabled", false);
}
});
});
</script>
First set data source to checkboxlist as your are doing
Then try this (Not tested, sorry for that)
for (int i = 0; i < chkList.Items.Count; i++)
{
if (Chkboxlist.Items[i].Value == "SomeValue")
{
Chkboxlist.Items[i].Enabled = false;
}
}

Gridview paging Show all Records

i have a gridview that has paging enabled. i also have a dropdown on the pager of the gridview where the user can select how many records per page they would like to retrieve. Once the dropdown is changed then an event is fired (shown below) to rerun the query with the updated results per page request. This works very well. I did however want to have a value "All" on the dropdown aswell and the method i used to impliment this is by disabling paging.
This all works brilliantly except for one issue. When the user selects "All" on the dropdown i would like to still show the pager once the gridview is updated. It doesnt show because i turned off paging but is there a way to show the pager again? See my code below for the event. (As you can see i renable the pager at the end but this has no effect)
thanks
damo
Code behind Event for Dropdown Change
void GridViewMainddl_SelectedIndexChanged(object sender, EventArgs e)
{
//changes page size
if ((((DropDownList)sender).SelectedValue).ToString() == "All")
{
GridViewMain.AllowPaging = false;
}
else
{
GridViewMain.PageSize = int.Parse(((DropDownList)sender).SelectedValue);
}
//binds data source
Result fAuditOverallStatusLatest = new Result(sConn);
GridViewMain.DataSource = Result.getAuditOverallStatusLatest();
GridViewMain.PageIndex = 0;
GridViewMain.DataBind();
GridViewMain.AllowPaging = true;
GridViewMain.BottomPagerRow.Visible = true;
GridViewMain.TopPagerRow.Visible = true;
}
DDL Code behind
protected void GridViewMain_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList GridViewMainddl = new DropDownList();
//adds variants of pager size
GridViewMainddl.Items.Add("5");
GridViewMainddl.Items.Add("10");
GridViewMainddl.Items.Add("20");
GridViewMainddl.Items.Add("50");
GridViewMainddl.Items.Add("100");
GridViewMainddl.Items.Add("200");
GridViewMainddl.Items.Add("500");
GridViewMainddl.Items.Add("All");
GridViewMainddl.AutoPostBack = true;
//selects item due to the GridView current page size
ListItem li = GridViewMainddl.Items.FindByText(GridViewMain.PageSize.ToString());
if (li != null)
GridViewMainddl.SelectedIndex = GridViewMainddl.Items.IndexOf(li);
GridViewMainddl.SelectedIndexChanged += new EventHandler(GridViewMainddl_SelectedIndexChanged);
//adds dropdownlist in the additional cell to the pager table
Table pagerTable = e.Row.Cells[0].Controls[0] as Table;
TableCell cell = new TableCell();
cell.Style["padding-left"] = "15px";
cell.Controls.Add(new LiteralControl("Page Size:"));
cell.Controls.Add(GridViewMainddl);
pagerTable.Rows[0].Cells.Add(cell);
//add current Page of total page count
TableCell cellPageNumber = new TableCell();
cellPageNumber.Style["padding-left"] = "15px";
cellPageNumber.Controls.Add(new LiteralControl("Page " + (GridViewMain.PageIndex + 1) + " of " + GridViewMain.PageCount));
pagerTable.Rows[0].Cells.Add(cellPageNumber);
}
}
Put this in your Page_Init:
GridViewMain.PreRender += new EventHandler(GridViewMain_PreRender);
Then elsewhere in your Page class:
void GridViewMain_PreRender(object sender, EventArgs e)
{
var pagerRow = (sender as GridView).BottomPagerRow;
if (pagerRow != null)
{
pagerRow.Visible = true;
}
}
Then for your drop down event:
void GridViewMainddl_SelectedIndexChanged(object sender, EventArgs e)
{
MyServices fServices = new FAServices(sConn);
Result fAuditOverallStatusLatest = new Result(sConn);
var data = Result.getAuditOverallStatusLatest();
//changes page size
if ((((DropDownList)sender).SelectedValue).ToString() == "All")
{
GridViewMain.PageSize = data.Count();
}
else
{
GridViewMain.PageSize = int.Parse(((DropDownList)sender).SelectedValue);
}
//binds data source
GridViewMain.DataSource = data;
GridViewMain.PageIndex = 0;
GridViewMain.DataBind();
GridViewMain.AllowPaging = true;
}
In that PreRender event, you'll have to duplicate that code for the top pager.
Edit: To get All selected, make this change in GridViewMain_RowCreated:
if (li != null)
{
GridViewMainddl.SelectedIndex = GridViewMainddl.Items.IndexOf(li);
}
else
{
GridViewMainddl.SelectedIndex = GridViewMainddl.Items.Count - 1;
}

Unable to FindControl() in ListView ItemEditing

I have a ListView in an ASP.NET web application. When a user clicks the edit button, I want textfields to pop up that are dependent on certain values of the item. However, I can't seem to find any controls inside of my ListView1_ItemEditing() function.
I have read the Microsoft documentation and various help threads on the internet, but their suggestions do not appear to work for me. This is generally what I see:
ListViewItem item = ProductsListView.Items[e.NewEditIndex];
Label dateLabel = (Label)item.FindControl("DiscontinuedDateLabel");
For the sake of simplicity I just want to be able to select a label in ListView1_ItemEditing(). This is the code in ListView1_ItemEditing():
protected void ListView1_ItemEditing(Object sender, ListViewEditEventArgs e)
{
DataBind(); //not sure if this does anything
ListViewItem item = ListView1.Items[e.NewEditIndex];
Label debugLabel = (Label)item.FindControl("label_editing");
debugLabel.Text = "Works";
}
Here is the ASP
<EditItemTemplate>
<asp:Label ID="label_editing" runat="server" Text="hello world"></asp:Label>
</EditItemTemplate>
When debugging, item and debugLabel are both NULL.
UPDATE: I resolved this issue by moving my logic to ItemDataBound and then checking if my tr (containing textboxes) was in that particular data item. Code below:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Control tr_verizon = e.Item.FindControl("tr_verizonEdit");
Control tr_att = e.Item.FindControl("tr_attEdit");
if (tr_verizon != null)
{
//Control tb_meid = e.Item.FindControl("TextBox_Meid");
Label lbl_carrierId = (Label)e.Item.FindControl("lbl_carrierId");
if (lbl_carrierId == null)
{
Message.Text = "lbl_carrierId is null!";
}
else if (lbl_carrierId.Text.Equals(""))
{
Message.Text = "lbl_carrierId is empty!";
}
else
{
string recordId = lbl_carrierId.Text;
if (tr_verizon != null && tr_att != null)
{
if (lbl_carrierId.Text.Equals("1"))
{
tr_verizon.Visible = false;
tr_att.Visible = true;
}
else
{
tr_verizon.Visible = true;
tr_att.Visible = false;
}
}
}
}
}
}
The ItemEditing event is raised when an item's Edit button is clicked, but before the ListView item is put in edit mode. Therefore controls in EditItemTemplate are not available at this time.
More Info and example
You should do the DataBind() first, like this:
ListView1.EditIndex = e.NewEditIndex;
ListView1_BindData(); // a function that get the DataSource and then ListView1.DataBind()
// Now find the control as you did before
Have you tried casting the sender object instead of trying to access your ListViewItem by index?
protected void ListView1_ItemEditing(Object sender, ListViewEditEventArgs e)
{
var item = sender as ListViewItem;
var debugLabel = item.FindControl("label_editing") as Label;
debugLabel.Text = "Works";
}

check/uncheckbox in gridview tracking

i have a below gridview control with a checkbox on it, so my question is when i hit on save button i able to find the checkbox which have been checked and till here no problem, but the problem started when the user tries to uncheck the checkedbox so how would i track the changes and save it into the db that has been checked. anyhelp?
List<Employee> result = new List<Employee>();
long Id = (long)Session["Id"];
result = Employee.GetEmployeeById(Id);
foreach (GridViewRow row in gv.Rows)
{
CheckBox chkBox = row.FindControl("chkSelected") as CheckBox;
if (c != null)
{
if (result.Count > 0)
{
foreach (Employee item in result)
{
Label Id = row.FindControl("lblId") as Label;
if (Id.Text == item.Id.ToString())
{
chkBox.Checked = true;
}
else
{
chkBox.Checked = false;
}
}
}
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<script language="javascript" type="text/javascript">
function SelectAll(cb)
{
var gvVar = document.getElementById("<%= gv.ClientID %>");
var cell;
if (gvVar.rows.length > 0)
{
for (i=1; i<gvVar.rows.length; i++)
{
cell = gvVar.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
cell.childNodes[j].checked = document.getElementById(cb).checked;
}
}
}
}
}
//--------------------------------------------------------------------------------------------.
function Select(cb)
{
var total = parseInt('<%= this.gv.Rows.Count %>');
var counter=0;
var cbSelectAll=document.getElementById(cb);
var gvVar = document.getElementById("<%= gv.ClientID %>");
var cell;
if (gvVar.rows.length > 0)
{
for (i=1; i<gvVar.rows.length; i++)
{
cell = gvVar.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
if(cell.childNodes[j].checked)
counter++;
else
counter--;
}
}
}
}
if(counter==total)
cbSelectAll.checked=true;
else if(counter<total)
cbSelectAll.checked=false;
}
</script>
//----------------------------------------------------------------------------------------
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
CheckBox cbSelect = (CheckBox)e.Row.Cells[0].FindControl("cbSelect");
CheckBox cbSelectAll = (CheckBox)this.gv.HeaderRow.FindControl("cbSelectAll");
cbSelect.Attributes.Add("onclick", "javascript:Select('" + cbSelectAll.ClientID + "')");
cbSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + cbSelectAll.ClientID + "')");
}
}
Yes, store the original value in a hidden field. If always starting with false, you could use JavaScript to set the hidden value to true when the user clicked the checkbox. Using JQuery, you could do:
<asp:TemplateField HeaderText="Select" ItemStyle-CssClass="Checked">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
<asp:HiddenField iD="dh" runat="server" />
</ItemTemplate>
</asp:TemplateField>
$("#<%= Grid.ClientID %>").find(".Checked > :checkbox").each(function() {
$(this).siblings("input[type='hidden']").attr("value", "True");
});
Something like that. On Server side, parse the value and if true, then you know it changed.
HTH.
It may not be the brightest idea, but you can query the database for the current state, and the compare with what you have got from the web page during a postback button click, or something like that. Or you can go with Brians answer.
It is possible to persist a list of objects into the Viewstate and access it in a consequent postback. The only thing is that the object you are trying to persist must be defined as serializable.
Update:
The ViewState approach
I feel this may be suitable for your need, and it requires a bit of linq. You'd need to create a class as follows:
[Serializable()]
public class OptionState
{
//the id of the item
int ID {get;set;}
//state of the checkbox
bool Checked {get;set;}
}
Note the Serializable attribute. This is required for the instance to persist to the viewstate.
Add the list of options to the viewstate:
var lstOptions = (from x in <your_option_store>
select new OptionState{ID = x.ID, Checked = x.Checked}).ToList();
ViewState.Add("options", lstOptions);
Here is a bit of code that should go into your button click:
foreach(GridViewRow row in gvOptions.Rows)
{
//not writing the bit of code
//which gets the ID and the
//state of checkbox of
//the gridview row being processed
OptionState currentState = GetOptionStateObjectFromRow(row);
List<OptionState> lstStates = (List<OptionState>) ViewState["options"];
OptionState originalState = lstStates.FirstOrDefault(x => x.ID == currentState.ID);
if(currentState.Checked != originalState.Checked)
{
//the appropriate db call needs to be done here.
}
}

Resources