In my Asp project, I have a radio button inside my gridview. The radio button only allows user to select once every time.
However when user clicks a radio button, a confirm message will appear and the record will only be saved if the user clicks "OK".
Everything is working, but now I'm facing a problem. The radio button oncheckedchanged seems to not fire when user clicks "OK". How can I fire the radio button event once the user clicks "Ok"?
Here is my code:
Javascript
function RadioCheck(rb) {
var gv = document.getElementById('Content_PageContent_ucSubMenuItem_module_sales_customer_submenuitem_contactpersonlist_ascx_gvContactPersonList');var rbs = gv.getElementsByTagName("input");
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "radio") {
//if radio button is check but not the selected value then false
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
return confirm('Confirm Save?');
}
client-side
<asp:TemplateField HeaderText="Default" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:RadioButton ID="rdbtnDefault" runat="server" onclick="RadioCheck(this);" oncheckedchanged="rdbtnDefault_CheckedChanged" Visible='<%#((string)Eval("DEFAULT")) == "Y" ? false : true %>'/>
<asp:Image ID="imgDefault" runat="server" Height="13px" ImageUrl="~/Styles/images/tick-48x48.png" Width="13px" Visible='<% ((string)Eval("DEFAULT")) == "Y" ? true : false %>' />
</ItemTemplate>
Server side
//--Register for in post back--
if (Page.ClientScript.IsClientScriptBlockRegistered(DataUCContactListing) == false) {
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "gvRdBtnSelectOnce", blcGenerateScript.gvRdBtnSelectOnce(gvContactPersonList.ClientID,true), true);
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "gvSelectAllChkBox", blcGenerateScript.gvSelectAllChkBox(gvContactPersonList.ClientID), true);
}
//**Register for script**
protected void rdbtnDefault_CheckedChanged(object sender, EventArgs e) {
try {
RadioButton lnBTNDone = (RadioButton)sender;
GridViewRow row = (GridViewRow)lnBTNDone.NamingContainer;
string accountID = gvContactPersonList.DataKeys[row.RowIndex].Values[0].ToString();
int contactID = int.Parse(gvContactPersonList.DataKeys[row.RowIndex].Values[1].ToString());
using (TransactionScope scope = new TransactionScope()) {
dlcCustomerDB.updateAccountOtherDefaultN(accountID);
dlcCustomerDB.updateAccountDefaultY(accountID, contactID);
scope.Complete();
}
createGridView();
this.Session[gbcMessageSessionID.message1] = gbcMessageAlert.saveSuccessfully;
Response.Redirect(Request.Url.ToString());
} catch (Exception ex) {
logger.Error(ex.Message);
throw;
}
}
Look into following URLs
http://www.asp.net/web-forms/tutorials/data-access/enhancing-the-gridview/adding-a-gridview-column-of-radio-buttons-vb
Radiobutton checked change event not firing in gridview
Please look into this code
<asp:RadioButton ID="rdbtnDefault" runat="server" onclick="return RadioCheck(this);" oncheckedchanged="rdbtnDefault_CheckedChanged" Visible='<%#((string)Eval("DEFAULT")) == "Y" ? false : true %>' AutoPostBack="True" />
I have added "return" keyword for onclick event of RadioButton.
Related
I have one button to change based on the page. I have 3 page which is confirmed, pending and rejected.
On confirmed and rejected the text inside the button is same but different for pending. How can change the word in the button. The button placed in the grid view.
Below the code in aspx file:
<asp:TemplateField>
<HeaderTemplate>Actions</HeaderTemplate>
<ItemTemplate>
<asp:Button ID="lnkbtnInfo" runat="server" CssClass="btn btn-success" Text="" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Id") %>' CommandName="Detail" /></td>
</ItemTemplate>
</asp:TemplateField>
How can i do in the cs file, to use the if else.
For rejected and confirmed page, the button is "view" and pending page is "review"
I figured that you need to use RowDataBound event handler on gridview and create if statement based on button's CommandArgument state:
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView.Rows.Count - 1; i++)
{
Button status = (Button)GridView.Rows[i].FindControl("lnkbtnInfo"); // find control from your button ID
String state = status.CommandArgument.ToString(); // assume the value given by Eval data binding
if (state.Equals("confirmed") || state.Equals("rejected"))
{
status.Text = "view";
}
else // if (state.Equals("pending"))
{
status.Text = "review";
}
}
}
Reference: Change button text in asp:gridview based on cell value C#
What you can also do is use Eval with ternary for changing Button Text on .aspx page,
Ternary Operator syntax
(your condition) ? "if true value":" if false value";
Here is Example " if you want to check that your 'Id' is 3 then Button Text should be View else It should be Review."
<asp:Button ID="lnkbtnInfo" runat="server" CssClass="btn btn-success" Text='<%# ((int)Eval("Id") == 3) ? "view":"Review" %>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Id") %>' CommandName="Detail" />
Here my answer that works on my situation:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
Button name = (Button)GridView1.Rows[i].FindControl("lnkbtnInfo"); // find control from your button ID
Label status= (Label)GridView1.Rows[i].FindControl ("lblStatus");
if (status.Text == "Complete" || status.Text == "Rejected" || status.Text == "Cancelled" ||
status.Text == "Returned" || status.Text == "UserRejected")//refer to confirm and reject order
{
name.Text = "View";
}
else // refer to pending order
{
name.Text = "review";
}
}
}
I have the following markup in an .aspx file:
<asp:Repeater ID="ListOfAssignments" runat="server" OnItemDataBound="ListOfAssignments_ItemDataBound">
<ItemTemplate>
<asp:Label ID="AssignmentID" runat="server" Text="Label"></asp:Label>
<br />
<asp:Label ID="PathToFile" runat="server" Text="Label"></asp:Label>
<br />
<asp:Button ID="RemoveAssignment" runat="server" Text="Remove" OnClick="RemoveAssignment_Click"/>
</ItemTemplate>
</asp:Repeater>
There are two labels and a button in a fairly standard repeater control. The repeater is bound to a database, and populates the labels with records from the database.
Here's my problem: I have a click event for each button in the repeater. The RemoveAssignment_Click method is called when the user clicks any of the buttons. In the click event, I want to know the text of the two labels associated with whatever button the user clicked.
What I mean is, in this method:
protected void RemoveAssignment_Click(object sender, EventArgs e)
{
//code goes here
}
I want to be able to know the text of the labels that are adjacent to the button that was clicked. How do I do that?
What you are looking for is the Button.OnCommand Method:
This allows you to create multiple Button controls on a Web page and
programmatically determine which Button control is clicked.
So inside ListOfAssignments_ItemDataBound you'd assign the CommandArgument to the button, where the CommandArgument is the ID of the article to be deleted:
protected void ListOfAssignments_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Button delButton = e.Item.FindControl("RemoveAssignment") as Button;
delButton.CommandArgument = //set to the value of AssignmentID
//rest of your code
}
}
And now your button should say to use your new OnCommand:
<asp:Button ID="RemoveAssignment" OnCommand="RemoveAssignment" runat="server" Text="Remove" />
And then you create the method:
protected void RemoveAssignment(object sender, CommandEventArgs e)
{
int articleIDToDelete = 0;
if (Int32.TryParse((string)e.CommandArgument, out articleIDToDelete))
{
//delete the article with an ID = articleIDToDelete
}
}
You can add CommandName and CommandArgument attributes to the button tag and use them as a hint. And then in your even handler you can do e.CommandName == "xxx" or e.CommandArgument == "xxx". You can also use CommandArgument to pass the actual strings. You just need to bind the data just like you would do with a label, text, etc:
<asp:Button ID="RemoveAssignment" runat="server" CommandArgument='<%#Eval("Label1")+","+ Eval("Label2")%>' Text="Remove" OnClick="RemoveAssignment_Click"/>
Then in the event handler you can do something like:
string[] args = e.CommandArgument.ToString().Split(new char[] {','});
string label1 = args[0];
string label2 = args[1];
This should get you going.
Hm, I know c# and wp but you should try to set a bool and use this logic: if it is false, repeat will continue and if it is true, it'll exit the repeat. try this:
bool exit;
void Button_Click(eventargs stuffy here)
{
exit = true,
}
void Repeat()
{
if (exit == false)
{
Repeat();
//Your code here
}
}
I have validation as below but only like to triggered if the checkbox is ticked.
<!-- TextBox and its validator -->
Name: <asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator runat="server"
ID="RequiredFieldValidator1"
Text="*"
ErrorMessage="Name is required"
ControlToValidate="TextBox1" />
Can I get it done using asp:RequiredFieldValidator?
I only like to validate if a certain condition matched.
Currently it is validating every time the 'Save' button is clicked.
Use a custom validator instead:
<asp:CustomValidator ID="cv1" runat="server"
ErrorMessage="Name is required"
Text="*"
ControlToValidate="TextBox1"
ValidateEmptyText="True"
ClientValidationFunction="validate" />
and the script (just checking a checkbox and the textbox value as example; you can use custom logic):
<script type="text/javascript">
function validate(s,args){
if(document.getElementById("<%= checkboxId.ClientID %>").checked){
args.IsValid = args.Value != '';
}
else{
args.IsValid = true;
}
}
</script>
This will do the client-side validation. If you need server validation also, add the OnServerValidate attribute, and a handler on code behind. See here for details.
I solved this easily by adding the following javascript on Client side.
ValidatorEnable(document.getElementById("RequiredFieldValidator1"), true); or
ValidatorEnable(document.getElementById("RequiredFieldValidator2"), false);
You can also try this one
protected void CheckBox_CheckedChanged(object sender, EventArgs e)
{
if(CheckBox.Checked)
{
RequiredFieldValidator1.Enabled = true;
RequiredFieldValidator1.ValidationGroup = "anything";
Button1.ValidationGroup = "anything";// your save button
}
else
{
RequiredFieldValidator1.Enabled = false;
RequiredFieldValidator1.ValidationGroup = string.Empty;
Button1.ValidationGroup = string.Empty; // save button
}
}
Try this...
protected void RequiredFieldValidator1_Load(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
RequiredFieldValidator1.Enabled = true;
}
else if (CheckBox1.Checked == false)
{
RequiredFieldValidator1.Enabled = false;
}
}
You can enabled/Disabled the RequiredFieldValidator from the Javascript/jQuery.
For your condition, When Checkbox is checked :- Just call the javascript function to enabled the RequiredFieldValidator and when its Uncheck just disabled the RequiredFieldValidator.
For other Conditions like Dropdown index change, textbox value change and radio button selection change you can call its onchange, onblur, onclick respectively and
After executing the required condition you can Enabled/Disabled the RequiredFieldValidator.
Hope this help you.
I want to prompt the user for confirmation when he tries to delete a record in a detail view? I have command filed in which showDeletebutton set to true.
I found how to do the confirmation for gridview, but how can I modify to match detail view?
Code:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// Must use LinkButton here instead of ImageButton
// if you are having Links (not images) as the command button.
ImageButton button = control as ImageButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
}
}
Anybody?
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px"
.....
<asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />
<asp:BoundField DataField="Quantity" HeaderText="Quantity"
SortExpression="Quantity" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="New" Text="New"></asp:LinkButton>
<asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView
This can be done easily on the markup code. I simply added the js code to the onClientClick property of the delete button:
OnClientClick="return confirm('Are you sure you want to delete this record');"
Or if you want do this in the code behind:
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
LinkButton bttn = (LinkButton)DetailsView1.FindControl("lnkDelete");
bttn.OnClientClick = "return confirm('Are you sure you want to delete this record!');";
}
I found the answer to my question.
My answer:
protected void DViewComputer_DataBound1(object sender, EventArgs e)
{
int noRow = DViewComputer.Rows.Count - 1;//get the no of record
if (noRow >0)
{
Button button = (Button)(DViewComputer.Rows[noRow].Cells[0].Controls[2]);
// Add delete confirmation
((System.Web.UI.WebControls.Button)(button)).OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
Anyways thanks for your help guys.
foreach (Control control in cell.Controls)
{
// Must use LinkButton here instead of ImageButton
// if you are having Links (not images) as the command button.
ImageButton button = control as ImageButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.Attributes.Add("onclick","your javascript here");
}
Please see the below URL......
http://www.codeproject.com/Articles/32756/ASP-NET-GridView-delete-confirmation-using-asp-Com
This corrects the OP's solution. The code was translated from the code found here: http://forums.aspfree.com/net-development-11/confirm-button-when-deleting-detailsview-120113-2.html
protected void dvEvent_DataBound(object sender, EventArgs e)
{
int commandRowIndex = dvEvent.Rows.Count - 1;
if (commandRowIndex > 0)
{
DetailsViewRow commandRow = dvEvent.Rows[commandRowIndex];
DataControlFieldCell cell = (DataControlFieldCell)commandRow.Controls[0];
foreach (Control ctrl in cell.Controls)
{
if (ctrl is ImageButton)
{
ImageButton ibt = (ImageButton)ctrl;
if (ibt.CommandName == "Delete")
{
ibt.ToolTip = "Click here to Delete";
ibt.CommandName = "Delete";
ibt.Attributes["onClick"] = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
}
}
}
I have a gridview with the onRowDeleting method implemented. I would like to prompt the user with a pop up message to confirm whether they wish to delete this item or not.
If the user clicks "OK", "Confirm" or something similar then I would like the onRowsDeleting to be process and the record deleted. But if the user pressed "No" then I would like the method to be cancelled and the record not deleted.
How can this be done?
Here is my gridview and onRowDeleting method in the code behind.
<asp:GridView runat="server" ID="gvShowQuestionnaires" HeaderStyle-CssClass="table_header" CssClass="view" AlternatingRowStyle-CssClass="alt" AlternatingRowStyle-BackColor="#f3f4f8" AutoGenerateColumns="False"
DataKeyNames='QuestionnaireID' OnRowDeleting="gvShowQuestionnaires_RowDeleting" OnRowEditing="gvShowQuestionnaires_RowEdit" OnSelectedIndexChanged="gvShowQuestionnaires_SelectedIndexChanged" FooterStyle-CssClass="view_table_footer" >
<Columns>
<asp:BoundField DataField="QuestionnaireID" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
<asp:BoundField DataField="QuestionnaireName" HeaderText="Questionnaire Name" />
<asp:ButtonField CommandName="select" ButtonType="Link" Text="view results" />
<asp:CommandField HeaderText="Options" CausesValidation="true" ShowDeleteButton="True" ShowEditButton="true" EditText="Edit">
</asp:CommandField>
</Columns>
</asp:GridView>
protected void gvShowQuestionnaires_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int questionnaireID = (int)gvShowQuestionnaires.DataKeys[Convert.ToInt32(e.RowIndex)].Value;
GetData.DeleteQuestionnaire(questionnaireID);
gvShowQuestionnaires.DataSource = DT;
gvShowQuestionnaires.DataBind();
lblActivity.Visible = true;
lblActivity.Text = "Your questionnaire has been deleted";
}
You should do that on clientside with javascript.
Therefore you can handle GridView's RowDataBound event to add this to the Delete-Button's OnClientClick:
protected void gvShowQuestionnaires_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// reference the Delete LinkButton
LinkButton db = (LinkButton)e.Row.Cells[3].Controls[0];
db.OnClientClick = "return confirm('Are you certain you want to delete this questionnaire?');";
}
}
http://msdn.microsoft.com/en-us/library/bb428868.aspx
This js-function will return whether the user clicked ok or cancel. If a js-eventhandler returns false, the page will not postback to the server.
The "return confirm(..") Javascript is on the right track.
The problem is that ASP.NET will append js to call __doPostBack
so you'll get something like this in your HTML for the delete button:
OnClickClient="return confirm('Are you sure you want to delete this record?');";javascript:__doPostBack('ctl00$Main$PlansGrid','Delete$101')"
What happens is:
1) User clicks Delete button.
2) Confirm dialog displayed.
3) User clicks on OK button.
4) Confirm returns True.
5) return at beginning of statement executes and __doPostBack is not called.
The solution is to return only if confirm returns false:
OnClientClick="if(!confirm('Are you sure you want to delete this Plan?')) return;"
If user clicks OK confirm returns True and then __doPostBack executes.
Simply call a JavaScript function returning a boolean by "return" caller so if returns false this link button will not work.
ASPX
<asp:LinkButton runat="server" OnClientClick="return DeleteItem();" locationID='<%# DataBinder.Eval (Container.DataItem,"Id").ToString() %>' ID="linkDelete" OnClick="linkDelete_Click" title='<%# "Delete " + DataBinder.Eval (Container.DataItem,"City").ToString() %>' Style="float: left;"><img src="Asset/img/icon/bin.gif" alt="" hspace="3" /></asp:LinkButton>
Javascript
<script type="text/javascript">
function DeleteItem() {
if (confirm("Delete this Location?")) {
return true;
} else {
return false;
}
}
</script>
Server Side
protected void linkDelete_Click(object sender, EventArgs e)
{
int locationID =0;
int.TryParse(((LinkButton)sender).Attributes["locationID"].ToString(),out locationID);
if (locationID > 0)
{
Location loc = Location.GetById(locationID);
CurrentDataContext.CurrentContext.DeleteObject(loc);
CurrentDataContext.CurrentContext.SaveChanges();
bindGv();
}
}
Another way:
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// Must use LinkButton here instead of ImageButton
// if you are having Links (not images) as the command button.
LinkButton button = control as LinkButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.OnClientClick = "return confirm('Are you sure " +
"you want to delete this record?');";
}
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string id = e.Row.Cells[2].Text;
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton db = (LinkButton)e.Row.Cells[6].Controls[0];
db.OnClientClick = "return confirm('Are you want to delete this Work Description : " + id + "?');";
}
}
Get by command button type
protected void gvShowQuestionnaires_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// handle the Command Column Index
var commandColumnIndex = GvOperators.Columns
.OfType<DataControlField>()
.Select((x, i) => new { Index = i, Column = x })
.FirstOrDefault(x => x.Column is CommandField)
.Index;
var commandButtons = e.Row.Cells[commandColumnIndex].Controls.OfType<LinkButton>();
// reference the Delete LinkButton
var db = commandButtons.FirstOrDefault(x => x.CommandName == "Delete");
if(db!=null)
db.OnClientClick = "return confirm('Are you certain you want to delete this questionnaire?');";
}
}