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";
}
}
}
Related
Actually I used read more and hide two button for if data More than 40 character ,it's working fine but it's refreshing the page when click on button how to disable the refresh. In Asp.net
code in .aspx file
<asp:TemplateField HeaderText="UserdetailsDescription" ItemStyle-Width="50">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server"
Text='<%# Limit(Eval("UserdetailsDescription"),40) %>'
Tooltip='<%# Eval("UserdetailsDescription") %>'>
</asp:Label>
<asp:LinkButton ID="ReadMoreLinkButton" runat="server"
Text="Read More"
autopostback="false"
Visible='<%# SetVisibility(Eval("UserdetailsDescription"), 40) %>'
OnClick="ReadMoreLinkButton_Click">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
##code Behind .CS file
## protected bool SetVisibility(object desc, int maxLength)
{
var description = (string)desc;
if (string.IsNullOrEmpty(description)) { return false; }
return description.Length > maxLength;
}
protected void ReadMoreLinkButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
GridViewRow row = button.NamingContainer as GridViewRow;
Label descLabel = row.FindControl("lblDescription") as Label;
button.Text = (button.Text == "Read More") ? "Hide" : "Read More";
string temp = descLabel.Text;
descLabel.Text = descLabel.ToolTip;
descLabel.ToolTip = temp;
}
protected string Limit(object desc, int maxLength)
{
var description = (string)desc;
if (string.IsNullOrEmpty(description)) { return description; }
return description.Length <= maxLength ?
description : description.Substring(0, maxLength) + ".....";
}
I think UpdatePnael and PostBackTrigger can help you partially update the page without full postback. Adding Update Panel surrounding your link button and adding PostBackTrigger can help in your situation. For more details see this answer
There is no autopostback attribute on a linkbutton as far as I know.
Try a OnClientClick instead and make sure to return false from the function that you call there.
<asp:LinkButton ID="ReadMoreLinkButton" runat="server"
Text="Read More"
Visible='<%# SetVisibility(Eval("UserdetailsDescription"), 40) %>'
OnClientClick="HideReadMoreLinkButton(); return false"/>
<script>
function HideReadMoreLinkButton() {
//your code to hide button here
}
</script>
Note: if you get a page postback by another button the button will go back to visible because that is that state it is in kept in viewstate. So an option there is to have a hidden field maintain it's client state and a bit of JS on the page to restore the links back to hidden.
See also: Disable the postback on an <ASP:LinkButton>
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.
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?');";
}
}
I have an ImageButton control as part of a GridView control that is displayed as an ItemTemplate and in the same GridView. I have a regular Button control to which I added some code like this
if (e.CommandName == "addToSession")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
string ISBN = selectedRow.Cells[0].Text;
string bookTitle = selectedRow.Cells[1].Text;
string image = selectedRow.Cells[2].Text;
//storing title, author, pictureUrl into session variables to 'carry them over' to RateBook.aspx
Service s = new Service();
Session["ISBN"] = ISBN;
Session["bookTitle"] = bookTitle;
Session["ImageUrl"] = s.returnImageUrl(bookTitle);
if (Session["userName"] == null)
{
Response.Redirect("registerPage.aspx");
}
else
{
Response.Redirect("RateBook.aspx");
}
}
else if (e.CommandName == "ratedBooks")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
string bookTitle = selectedRow.Cells[1].Text;
Service s = new Service();
Session["ImageUrl"] = s.returnImageUrl(bookTitle);
Response.Redirect("BookRated.aspx");
}
when I run this code I get a format exception and again I am not sure why. I have altered the image button a bit and nested the image in a link button which seems to be more correct.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="ratedBooks">
<asp:Image ID="ImageButton1" ImageUrl='<%#Eval("pictureUrl") %>' runat="server" />
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Please advise.
Regards,
Arian
I believe you can accomplish your needs with an ImageButton, as it supports all the major Button functionality, including CommandName (see http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.imagebutton.commandname.aspx).
Try this out:
<asp:ImageButton ID="LinkButton1" runat="server"
CommandName="ratedBooks"
ImageUrl='<%#Eval("pictureUrl") %>' />
Also, note that your format exception could be coming from the lines that read:
Convert.ToInt32(e.CommandArgument);
The reason being that there appears from this code snippet to be no value assigned to the CommandArgument of the button. Convert.ToInt32 requires a valid integer value to be passed in, which means that the ImageButton needs to have a number bound to its CommandArgument property.
If you based your solution on this MSDN reference (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewcommandeventargs.aspx), note that the <asp:ButtonField> column type gets special treatment; the CommandArgument is set to the row index. When you use a template field, ASP.NET requires you to specify or data bind your own command argument.
Update
This question contains details on binding the grid view row index to a custom button:
ASP.NET GridView RowIndex As CommandArgument
A possible solution is to add the ItemDataBound event handler and search for the image button change its image url.
MyGrid.RowDataBound += new RepeaterItemEventHandler(MyGrid_RowDataBound);
void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex > -1)
{
ImageButton image = e.Row.FindControl("MY_IMAGE_CONTROL") as ImageButton;
image.ImageUrl = "PATH_TO_IMAGE";
}
}
Hope it helps.
You need CommandArgument
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" CommandName="Delete" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" ImageUrl="~/Modelos/Img/deleted.gif" />
</ItemTemplate>
</asp:TemplateField>
code behind C#
public void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
string t;
if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = grid1.Rows[index];
t = selectedRow.Cells[2].Text;
}
}
On ASPX
<asp:GridView ID="grid1" runat="server" onselectedindexchanged="GridView1_SelectedIndexChanged" ...