How to use confirm before chekboxchanged in asp.net? - c#

I use checkbox control in gridview i want to show confirm before checkboxchanged event.
Confirm box is asking question but not postback it, doing nothing...
// CS
TemplateField field = new TemplateField(){
HeaderText = "AKTIF",
ItemTemplate = new AddTemplateToGridView("AKTIF")
};
field.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
field.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
field.ItemStyle.Width = Unit.Pixel(40);
newXGrid.Columns.Add(field);
// ITEMPLATE
public class AddTemplateToGridView : ITemplate
{
String columnName;
public AddTemplateToGridView(String colname)
{
columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
if (columnName == "AKTIF")
{
CheckBox chk = new CheckBox() { ID="chkAktif", AutoPostBack=true };
chk.Attributes.Add("onclick","return confirm('Are you sure ?')");
chk.CheckedChanged += new EventHandler(l_CheckedChanged);
container.Controls.Add(chk);
}
}
void l_CheckedChanged(object sender, EventArgs e)
{
...
}
}
// My checkbox on page
<input id="ctl00_MainContent_ctl11_ctl02_chkAktif" type="checkbox" name="ctl00$MainContent$ctl11$ctl02$chkAktif" onclick="return confirm('Are you sure ?');setTimeout('__doPostBack(\'ctl00$MainContent$ctl11$ctl02$chkAktif\',\'\')', 0)">

Change this:
chk.Attributes.Add("onclick","return confirm('Are you sure ?')");
to this:
chk.Attributes.Add("onclick","if (!confirm('Are you sure ?')) return false;");
Set AutoPostBack="true" for the Checkbox to trigger the postback on click.

You are preventing javascript to execute setTimeout() by using return with confirm dialog.
Try this:
if(confirm('Are you sure?'))
setTimeout('__doPostBack(\'ctl00$MainContent$ctl11$ctl02$chkAktif\',\'\')', 0);
else
return false;

Related

Database Records on Page Load - Dynamic Text Fields

I am working with dynamically created text fields. Most solutions I have found thus far have been related to retaining view state on postback, but I believe I have taken care of that issue. On postback, the values that are in the text fields are retained.
The issue I am having: I can't get the database values currently stored to load in the dynamic fields. I am currently calling loadUpdates() to try to do this, but unsure how to grab the data row, while also making sure I can continue to add new fields (or remove them). How can I achieve this?
"txtProjectsUpdate" is the text field, "hidFKID" is the foreign key to a parent table, and "hidUpdateID" is the hidden value of the primary key in the child table (the values I am attempting to load).
Markup:
<div>
<asp:Button ID="btnAddTextBox" runat="server" Text="Add" OnClick="btnAddTextBox_Click" />
<asp:Placeholder ID="placeHolderControls" runat="server"/>
</div>
<asp:TextBox runat = "server" ID = "hidUpdateID" />
<asp:HiddenField runat = "server" ID = "hidFKID" />
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
for (var i = 0; i < TextBoxCount; i++)
AddTextBox(i);
}
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt = selectDetails();
tryHidFKID(hidFKID, dt.Rows[0]["fkprjNumber"].ToString());
loadUpdates();
}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
AddTextBox(TextBoxCount);
TextBoxCount++;
}
private int TextBoxCount
{
get
{
var count = ViewState["txtBoxCount"];
return (count == null) ? 0 : (int)count;
}
set { ViewState["txtBoxCount"] = value; }
}
private void btnRemove_Click(object sender, EventArgs e)
{
var btnRemove = sender as Button;
if (btnRemove == null) return;
btnRemove.Parent.Visible = false;
}
private void AddTextBox(int index)
{
var panel = new Panel();
panel.Controls.Add(new TextBox
{
ID = string.Concat("txtProjectUpdates", index),
Rows = 5,
Columns = 130,
TextMode = TextBoxMode.MultiLine,
CssClass = "form-control",
MaxLength = 500
});
panel.Controls.Add(new TextBox
{
ID = string.Concat("hidUpdateID", index)
});
var btn = new Button { Text = "Remove" };
btn.Click += btnRemove_Click;
panel.Controls.Add(btn);
placeHolderControls.Controls.Add(panel);
}
protected void loadUpdates()
{
DataTable dt = dbClass.ExecuteDataTable
(
"spSelectRecords", <db>, new SqlParameter[1]
{
new SqlParameter ("#vFKPrjNumber", hidFKID.Value)
}
);
AddTextBox(TextBoxCount);
TextBoxCount++;
}
protected void tryHidFKID(HiddenField hidFKID, string txtSelected)
{
try
{
hidFKID.Value = txtSelected;
}
catch
{
hidFKID.Value = "";
}
}

Access dynamically created checkbox values in c#

I have added a CheckBox dynamically in asp.net
CheckBox cb = new CheckBox();
cb.Text = "text";
cb.ID = "1";
I can access this CheckBox via c# in pageLoad itself, just after declaring above codes.
But when I try to access this values after a button click I'm getting null values.
CheckBox cb1 = (CheckBox)ph.FindControl("1");
Response.Write(cb1.Text);
ph.Controls.Add(cb);
(ph is a placeholder)
Can any one tell me whats wrong here?
You need to recreate the checkbox everytime the page posts back, in Page_Load event, as it's dynamically added to page.
Then you can access the checkbox later in button click event.
// Hi here is updated sample code...
Source
<body>
<form id="frmDynamicControl" runat="server">
<div>
<asp:Button ID="btnGetCheckBoxValue" Text="Get Checkbox Value" runat="server"
onclick="btnGetCheckBoxValue_Click" />
</div>
</form>
</body>
code behind
protected void Page_Load(object sender, EventArgs e)
{
CheckBox cb = new CheckBox();
cb.Text = "text";
cb.ID = "1";
frmDynamicControl.Controls.Add(cb);
}
protected void btnGetCheckBoxValue_Click(object sender, EventArgs e)
{
CheckBox cb1 = (CheckBox)Page.FindControl("1");
// Use checkbox here...
Response.Write(cb1.Text + ": " + cb1.Checked.ToString());
}
After you click the button it will post back the page which will refresh the state. If you want the values to be persistent then you'll need to have them backed inside the ViewState or similar.
private bool CheckBox1Checked
{
get { return (ViewState["CheckBox1Checked"] as bool) ?? false; }
set { ViewState["CheckBox1Checked"] = value; }
}
void Page_load(object sender, EventArgs e)
{
CheckBox cb = new CheckBox();
cb.Text = "text";
cb.ID = "1";
cb.Checked = CheckBox1Checked;
cb.OnCheckedChanged += CheckBox1OnChecked;
// Add cb to control etc..
}
void CheckBox1OnChecked(object sender, EventArgs e)
{
var cb = (CheckBox)sender;
CheckBox1Checked = cb.Checked;
}
I'm a bit later here, but i just do:
try{
if(Request.Form[checkboxId].ToString()=="on")
{
//do whatever
}
}catch{}
If a checkbox is not checked, it will not appear in the Form request hence the try catch block. Its quick, simple, reusable, robust and most important, it just works!

How do I disable a dropdownlist item based on a user selection on another drop down in ASP.NET?

I have two drop down lists with a handful of items.
If the user selects X, X needs to be disabled from the next drop down.
If the user selects Y, Y needs to be disabled from the next drop down.
And vice-versa.
I tried this but it is not working:
protected void ddlSearchColumn1_SelectedIndexChanged(object sender, EventArgs e)
{
var ddl = (DropDownList) sender;
string itemSelected = ddl.SelectedValue;
ddlSearchColumn2.Items.FindByValue(itemSelected).Enabled = false;
}
Can anyone give me a hand?
You were very close:
MarkUP:
List 1: <asp:DropDownList ID="ddlSearchColumn1" runat="server" OnSelectedIndexChanged="ddlSearchColumn1_SelectedIndexChanged" AutoPostBack="true" />
List 2: <asp:DropDownList ID="ddlSearchColumn2" runat="server" AutoPostBack="true" />
Code Behind:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{//JUST PUT SOMETHING IN THE DROPDOWN BOXES
var items1 = new List<ListItem>()
{
new ListItem("Select Option"),
new ListItem("Test 1"),
new ListItem("Test 2"),
new ListItem("Test 3")
};
var items2 = new List<ListItem>()
{
new ListItem("Select Option", ""),
new ListItem("DDL 2 Test 1"),
new ListItem("DDL 2 Test 2"),
new ListItem("DDL 2 Test 3")
};
ddlSearchColumn1.DataSource = items1;
ddlSearchColumn1.DataBind();
ddlSearchColumn2.DataSource = items2;
ddlSearchColumn2.DataBind();
}
}
protected void ddlSearchColumn1_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list == null || list.SelectedValue.ToLower() != "test 1") // OR WHATEVER YOUR CRITERIA IS
return;
ddlSearchColumn2.Items.FindByValue("DDL 2 Test 1").Attributes.Add("Disabled", "Disabled");
}
}
IF you are interested in a client side solution:
With jQuery:
List 1: <asp:DropDownList ID="ddlSearchColumn1" runat="server" />
List 2: <asp:DropDownList ID="ddlSearchColumn2" runat="server" />
<script>
jQuery('#<%= ddlSearchColumn1.ClientID %>').change(function ()
{
if (jQuery(this).val() != 'Test 1')//CHANGE YOUR CRITERIA
return;
jQuery('#<%= ddlSearchColumn2.ClientID %> option[value="DDL 2 Test 1"]').attr('disabled', 'disabled');
});
</script>
Just using javascript no library:
List 1: <asp:DropDownList ID="ddlSearchColumn1" runat="server" />
List 2: <asp:DropDownList ID="ddlSearchColumn2" runat="server" />
<script>
document.getElementById('<%= ddlSearchColumn1.ClientID %>').onchange = function ()
{
var orgDdl = document.getElementById('<%= ddlSearchColumn1.ClientID %>');
var org2ddl = document.getElementById('<%= ddlSearchColumn2.ClientID %>');
if (orgDdl.value != 'Test 1')
return;
for (var i = 0, ii = org2ddl.options.length; i < ii; i++)
{
if (org2ddl.options[i].value == "DDL 2 Test 1")
{
org2ddl.options[i].disabled = "disabled";
break;
}
}
};
</script>
For some reason, this worked for me:
if (ddlState.SelectedValue == "AK")
{
MyDdl.Items.FindByValue("1111111").Enabled = false;
}
protected void ddlFirst_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListItem item in ddlSecond.Items)
{
if (item.ToString() == ddlFirst.SelectedValue)
{
item.Attributes.Add("disabled", "disabled");
}
}
}
protected void ddlSecond_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListItem item in ddlFirst.Items)
{
if (item.ToString() == ddlSecond.SelectedValue)
{
item.Attributes.Add("disabled", "disabled");
}
}
}
But I still believe this is client side thing
The DropDownList contains a collection of ListItem objects, which have the property Enabled you are trying to set. This property works for ListItems in RadioButtonList or CheckBoxList controls, but NOT DropDownList.
MSDN reference:
http://msdn.microsoft.com/en-us/library/vstudio/system.web.ui.webcontrols.listitem.enabled(v=vs.100).aspx
"Note: You cannot use this property to disable a ListItem control in a
DropDownList control or ListBox control."
Edit: Answers above solve your problem as you described, and I learned something new :)
I figured I'd add here.
Two things we forgot to add:
EnableViewState="True" AutoPostBack="True"
If you don't add those to the control, the event is not fired.

ASP Text box ID assignment using a for loop.?

I am a noob and i've been trying to figure out how we may assign an ID to asp:TextBox tags on creation in ASP.NET using c#.
Example:
I need to create a thread that may have multiple textboxes.
When a user clicks on a button, a text box must be generated with an ID say, txt01. On being clicked the second time, the ID of the generated text box must be txt02 and so on..depending on the number of clicks.
Thanks in Advance.
Remember last ID in some variable, for example int lastID, then in button's onClick method when creating the new TextBox assign its ID="txt"+lastID;.
You have to persist the lastID during page postbacks, you can store it in a ViewState.
Take and placeholder in your aspx page: eg: <asp:PlaceHolder runat="server" ID="pholder" />
and in code behind:
TextBox txtMyText = new TextBox();
tb1.ID = YourDynamicId;
pholder.Controls.Add(txtMyText);
You can save current id in ViewState and get the same id and assign incremented id to your dynamic textbox.
Try This:
int i = 1;
if (ViewState["i"] == null)
{
ViewState["i"] = i;
}
else
i = (int)ViewState["i"];
PlaceHolder1.Controls.Clear();
for (int j = 1; j <= i; j++)
{
TextBox TextBox = new TextBox();
TextBox.ID = "TextBox" + j.ToString();
PlaceHolder1.Controls.Add(TextBox);
}
ViewState["i"] = i + 1;
add this on your .aspx page
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
Hope This help.
I think this is what you are looking for -
You will notice that I have used Page_Init because if you create/add the controls in Page_Load then FindControl will return null in PostBack. And also any data you entered in the dynamically added controls will not persist during Postbacks.
But Page_Init is called before ViewState or PostBack data is loaded. Therefore, you can not use ViewState or any other controls to keep the control count. So I have used Session to keep the count.
Try it out and let me know what you think.
ASPX Page
<form id="form1" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="btnCreate" runat="server" Text="Create" OnClick="btnCreate_Click" />
<asp:Button ID="btnRead" runat="server" Text="Read" OnClick="btnRead_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
Code Behind
protected int NumberOfControls
{
get { return Convert.ToInt32(Session["noCon"]); }
set { Session["noCon"] = value.ToString(); }
}
private void Page_Init(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
//Initiate the counter of dynamically added controls
this.NumberOfControls = 0;
else
//Controls must be repeatedly be created on postback
this.createControls();
}
private void Page_Load(object sender, System.EventArgs e)
{
}
protected void btnCreate_Click(object sender, EventArgs e)
{
TextBox tbx = new TextBox();
tbx.ID = "txtData"+NumberOfControls;
NumberOfControls++;
PlaceHolder1.Controls.Add(tbx);
}
protected void btnRead_Click(object sender, EventArgs e)
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = (TextBox)PlaceHolder1.FindControl("txtData" + i.ToString());
//Add the Controls to the container of your choice
Label1.Text += tx.Text + ",";
}
}
private void createControls()
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = new TextBox();
tx.ID = "txtData" + i.ToString();
//Add the Controls to the container of your choice
PlaceHolder1.Controls.Add(tx);
}
}
store the id in a ViewState something like this
First initialise a count variable similiar to this.
in your class write this
protected int replyCount //declare the variable
{
get { return (int)ViewState["replyCount"]; }
set { ViewState["replyCount"] = value; }
}
In your page Load write this to initialise the replyCount if its not a postback;
protected void Page_Load(object sender, EventArgs e)
{
if(!page.IsPostBack)
{
replyCount = 0; //initialise the variable
}
}
then while creating dynamic textboxes
protected void Button_Click(Object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.id = "tb" + replycount; //use the variable
replycount++; // and after using increment it.
form.controls.add(tb); // assuming your form name is "form"
}
Thats it you should do.

TemplateControl Checkbox Event in Custom GridView Control

I have a custom GridView Control where I grab data from the database to populate the control. On the page I have also created a HeaderTemplate checkbox control and an ItemTemplate checkbox control:
<nm:ContactGridViewControl runat="server" ID="grdContacts">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox runat="server" AutoPostBack="true" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</nm:ContactGridViewControl>
I populate the GridView as follows in the OnInit event. I Chose not to repopulate on every postback because it was slowing down the app.
protected override void OnInit(EventArgs e)
{
this.RowDataBound += new GridViewRowEventHandler(ContactGridViewControl_RowDataBound);
this.RowCreated += new GridViewRowEventHandler(ContactGridViewControl_RowCreated);
if (!Page.IsPostBack)
{
List<EnquiryItem> contactList = new List<EnquiryItem>();
DataTable list = new DataTable();
if (SessionManager.LoginState != null)
{
contactList = SiteDataLayerHandler.GetContactList(SessionManager.LoginState.UserID);
}
if (contactList != null)
{
list.Columns.Add("LeadID");
list.Columns.Add("Name");
list.Columns.Add("Email Address");
foreach (EnquiryItem item in contactList)
{
DataRow row = list.NewRow();
row["LeadID"] = item.LeadID;
row["Name"] = string.Format("{0} {1}", item.FirstName.ToCapitalize(), item.LastName.ToCapitalize());
row["Email Address"] = item.EmailAddress;
list.Rows.Add(row);
}
this.DataSource = list;
this.DataBind();
}
}
base.OnInit(e);
}
In order to keep all code associated with the control in one place I have added a 'CheckedChanged' event dynamically on 'OnRowDataBound' This is just for the Checkbox in the HeaderTemplate. The Reason is so I can use this checkbox as a 'Select/Deselect All Rows':
protected void ContactGridViewControl_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == -1) // Check if row is Header row
{
CheckBox chk = e.Row.GetAllControls().OfType<CheckBox>().FirstOrDefault();
if (chk != null)
{
chk.CheckedChanged += new EventHandler(chk_CheckedChanged);
}
}
}
I then have the event code on the same page like so:
protected void chk_CheckedChanged(object sender, EventArgs e)
{
bool isChecked = ((CheckBox)sender).Checked;
foreach (GridViewRow row in this.Rows)
{
CheckBox chkBox = row.Cells[0].Controls[0] as CheckBox;
if (chkBox != null)
{
chkBox.Checked = isChecked;
}
}
}
This is where the problems start. My event never gets hit! However, the checkbox does postback.
Ok so the answer is this. I needed to assign the CheckedChanged event on the 'OnRowCreated' event instead of 'OnRowDataBound'
protected override void OnRowCreated(GridViewRowEventArgs e)
{
if (e.Row.RowIndex == -1)
{
CheckBox chk = e.Row.GetAllControls().OfType<CheckBox>().FirstOrDefault();
if (chk != null)
{
chk.CheckedChanged += new EventHandler(chk_CheckedChanged);
}
}
base.OnRowCreated(e);
}
This way the event hits the method everytime

Categories

Resources