How to change ButtonField text in asp.net - c#

<asp:TemplateField HeaderText="ID" SortExpression="CareerFormID">
<ItemTemplate>
<asp:Label ID="CareerFormID" runat="server" Text='<%#Eval("CareerFormID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Checked" DataField="checked" />
<asp:ButtonField Text="Edit" CommandName="Select" ButtonType="Link" />
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string idtemp = (GridView1.SelectedRow.FindControl("CareerFormID") as Label).Text;
Session["CompanyFormID"] = idtemp;
Response.Redirect("Management_Edit.aspx");
//Response.Write(Session["CompanyFormID"]);
}
I want to change ButtonField text="Modify" when DataField="checked" is 1, How can I do this?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[4].Text == "1")
{
e.Row.Cells[4].Text = "Yes";
e.Row.Cells[4].ForeColor = System.Drawing.Color.Green;
e.Row.Cells[6].Text = "Modify";
}
else if (e.Row.Cells[4].Text == "0")
{
e.Row.Cells[4].Text = "No";
e.Row.Cells[4].ForeColor = System.Drawing.Color.Red;
}
}
}
But this don't work, the cells[6] text is changed but the link is cancel.
For Example like that, the link can not working when I change the text
http://i.imgur.com/CN5snv6.jpg

Makes event handler when DataField="checked" is 1 (I don't find it in your code, how to make it to 1) and do this
//begin of event handler
//check datafield="checked" is 1, I still don't get it this one
ButtonField.Text="Modify"
//end of event handler

Related

ASP.net prevent gridview row click in edit mode

I have some issue with ASP.net Gridview that I hope people here can help me.
Requirements
Gridview whole row to be clickable to open another page
In editing mode, can change table values through edititemtemplate textbox
Problem
Textbox selection causes the entire row click event to fire and prevents user from changing the textbox text. User can edit table value without opening different page.
ASP Page
<asp:GridView ID="remarksGV1" runat="server" AllowPaging="true" DataKeyNames="REM_ID"
OnRowDataBound="remarksGV1_RowDataBound" OnSelectedIndexChanged="remarksGV1_SelectedIndexChanged"
OnRowEditing="remarksGV1_RowEditing"
OnRowCancelingEdit="remarksGV1_RowCancelingEdit"
OnRowUpdating="remarksGV1_RowUpdating"
AutoPostBack="false"
HeaderStyle-CssClass="thead-dark"
CssClass="table table-striped thead-dark table-borderless table-hover border-0 hand"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="No.">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:Label ID="titleLbl" runat="server" Text='<%# Bind("REM_TITLE") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="titleTB" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="REM_DESC" HeaderText="Remarks Description" ReadOnly="true" />
<asp:BoundField DataField="CREATE_DATE" DataFormatString="{0:d}" HeaderText="Date Created" ReadOnly="true" />
<asp:BoundField DataField="UPD_DATE" DataFormatString="{0:d}" HeaderText="Last Updated" ReadOnly="true" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Edit" ID="EditBtn" CssClass="btn-action" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button Text="Update" ID="UpdateBtn" CssClass="btn-action" runat="server" CommandName="Update" />
<asp:Button Text="Cancel" ID="CancelBtn" CssClass="btn-action" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
private void BindGrid()
{
Debug.WriteLine("BindGrid called");
int proj_code = Int32.Parse(ViewState["proj_cd"].ToString());
ProjectRepository remarksRepository = new ProjectRepository();
var remarks = remarksRepository.GetRemarks(proj_code, proj_task_code, proj_stask1_cd, proj_stask2_cd);
remarksGV1.DataSource = remarks;
remarksGV1.DataBind();
}
protected void Unnamed_Click(object sender, EventArgs e)
{
Launch.PageEvent(this, (LinkButton)sender, ViewState["proj_cd"].ToString());
}
protected void remarksGV1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
switch (e.Row.RowType)
{
case DataControlRowType.Header:
//...
break;
case DataControlRowType.DataRow:
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(remarksGV1, "Select$" + e.Row.RowIndex.ToString()));
break;
}
}
catch
{
//...throw
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox titleTB = (e.Row.FindControl("titleTB") as TextBox);
int prj_cd = Int32.Parse(ViewState["proj_cd"].ToString());
ProjectRepository repository = new ProjectRepository();
var remarks = repository.GetRemarks(prj_cd, proj_task_code, proj_stask1_cd, proj_stask2_cd);
Debug.WriteLine("Remarks Count: " + remarks.Count);
TMS_PROJ_REMARK remark = remarks.First(x => x.REM_ID == Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "REM_ID")));
if (titleTB != null)
{
titleTB.Text = remark.REM_TITLE;
}
}
}
protected void remarksGV1_SelectedIndexChanged(object sender, EventArgs e)
{
int row = remarksGV1.SelectedIndex;
long rem_id = (long)remarksGV1.DataKeys[row]["REM_ID"];
Debug.WriteLine("REM ID: " + rem_id);
Session["edit_remarks"] = true;
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs["rem_id"] = rem_id.ToString();
pairs["proj_cd"] = ViewState["proj_cd"].ToString();
Launch.ToPage(this, "Project_Remarks_In_2.aspx", pairs);
}
protected void btnAddRemarks_Click(object sender, EventArgs e)
{
Session["new_remarks"] = true;
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs["proj_cd"] = ViewState["proj_cd"].ToString();
string url = "Project_Remarks_In_1.aspx";
Launch.ToPage(this, url, pairs);
}
private void SetTitle()
{
ProjectRepository repository = new ProjectRepository();
TMS_PROJ_MASTER project = repository.GetProject(Convert.ToInt32(ViewState["proj_cd"]));
this.Title = "Remarks - " + project.PROJ_TITLE;
}
protected void remarksGV1_RowEditing(object sender, GridViewEditEventArgs e)
{
remarksGV1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void remarksGV1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Do stuff
ProjectRepository repository = new ProjectRepository();
GridViewRow row = remarksGV1.Rows[e.RowIndex];
TextBox titleTB = (row.FindControl("titleTB") as TextBox);
long rem_id = Convert.ToInt64(remarksGV1.DataKeys[e.RowIndex].Value);
var db = new THPEntities();
TMS_PROJ_REMARK remark = db.TMS_PROJ_REMARK
.First(x => x.REM_ID == rem_id);
remark.REM_TITLE = titleTB.Text;
remark.UPD_DATE = DateTime.Now;
db.SaveChanges();
// Bind Grid
remarksGV1.EditIndex = -1;
BindGrid();
}
protected void remarksGV1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
remarksGV1.EditIndex = -1;
BindGrid();
}
I suggest in this part of your code, do not add the full line click when you edit the line (I have add one -if- to check for the edit).
switch (e.Row.RowType)
{
case DataControlRowType.Header:
//...
break;
case DataControlRowType.DataRow:
if((e.Row.RowState & DataControlRowState.Edit) != DataControlRowState.Edit)
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(remarksGV1, "Select$" + e.Row.RowIndex.ToString()));
break;
}

Call Code Behind method (function) in RowCreated Gridview's handler

I want to call a Code Behind method inside a Gridview.
This is the Code Behind method that loops through every webcontrol that’s in the form:
private void SetupJSdataChange(Control parentControl)
{
foreach (Control control in parentControl.Controls)
{
//Response.Write(control.ID + "<br>");
if (control is WebControl)
{
WebControl webControl = control as WebControl;
webControl.Attributes.Add("onchange", "InputChanged(this)");
}
}
}
And I want it to loop through every webcontrol that’s in a RowCreated gridview's handler instead. This is my try:
protected void GVTrabajadores_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (Control control in parentControl.Controls)
{
//Response.Write(control.ID + "<br>");
if (control is WebControl)
{
WebControl webControl = control as WebControl;
webControl.Attributes.Add("onchange", "InputChanged(this)");
}
}
}
}
But I get an error that says "the name 'parentControl' doesn't exist in the current context" and I don't know how to handle it.
And this is the Gridview:
<asp:GridView ID="GVTrabajadores" runat="server"
CssClass="table table-hover table-striped"
ShowHeaderWhenEmpty = "true"
GridLines="None"
AutoGenerateColumns="False"
ShowFooter="true"
OnRowCreated="GVTrabajadores_RowCreated"
OnRowCommand="GVTrabajadores_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Nombre">
<ItemTemplate>
<asp:TextBox ID="TxNombre" runat="server" Text='<%#Eval("nombre") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxNombref" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cerrada">
<ItemTemplate>
<asp:CheckBox ID="CBCerrada" runat="server" Checked='<%# (Eval("cerrada").ToString() == "1" ? true : false) %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="CBCerradaf" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This should work for you. Note that I used generic event args - if you need them you'll need to change them.
private void GVTrabajadores_RowCreated(object sender, GridViewRowEventArgs e)
{
GridView gV = sender as GridView;
for(int i = 0; i < gV.Columns.Count; i++)
{
Control c = e.Row.Cells[i].Controls[0];
string controlType = c.GetType().ToString().Replace("System.Web.UI.WebControls.", "");
switch (controlType)
{
case "TextBox":
TextBox t = c as TextBox;
t.TextChanged += GVTrabajadores_TextBox_TextChanged;
t.AutoPostBack = true;
break;
case "CheckBox":
CheckBox cB = c as CheckBox;
cB.CheckedChanged += GVTrabajadores_CheckBox_Changed;
cB.AutoPostBack = true;
break;
}
}
}
private void GVTrabajadores_CheckBox_Changed(object sender, EventArgs e)
{
//process change
}
private void GVTrabajadores_TextBox_TextChanged(object sender, EventArgs e)
{
//process changed text
}

How to fire click event of the LinkButton in gridview and Show PopUp window in asp.net

I have tried to build one gridview with dynamic columns based the data source using the template fields in asp.net through code behind.
For that, to implement we have developed one class DynamicTemplate which implements the ITemplate interface. In that template fields i have inserted the LinkButton in each cell and when i click that cell link button i need to show the one Popup with selected cell value.
For Detailed Sample Please download from this link
For that I have created one Default.asxp page and wrote the following.
public partial class Default : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenateGridView();
}
private void GenateGridView()
{
TemplateField tempField;
DynamicTemplate dynTempItem;
LinkButton lnkButton;
Label label;
GridView gvDynamicArticle = new GridView();
gvDynamicArticle.Width = Unit.Pixel(500);
gvDynamicArticle.BorderWidth = Unit.Pixel(0);
gvDynamicArticle.Caption = "<div>Default Grid</div>";
gvDynamicArticle.AutoGenerateColumns = false;
DataTable data = getBindingData();
for (int i = 0; i < data.Columns.Count; i++)
{
tempField = new TemplateField();
dynTempItem = new DynamicTemplate(ListItemType.AlternatingItem);
lnkButton = new LinkButton();
lnkButton.ID = string.Format("lnkButton{0}", i);
lnkButton.Visible = true;
string ColumnValue = data.Columns[i].ColumnName;
tempField.HeaderText = ColumnValue;
if (ColumnValue == "EmpName")
{
label = new Label();
label.ID = string.Format("Label{0}", i);
dynTempItem.AddControl(label, "Text", ColumnValue);
label.Width = 100;
}
else
{
dynTempItem.AddControl(lnkButton, "Text", ColumnValue);
lnkButton.Click += lnkButton_Click;
}
tempField.ItemTemplate = dynTempItem;
gvDynamicArticle.Columns.Add(tempField);
//////grdUserPivotDateTwo.Columns.Add(tempField);
}
gvDynamicArticle.DataSource = data;
gvDynamicArticle.DataBind();
divContainer.Controls.Add(gvDynamicArticle);
}
void lnkButton_Click(object sender, EventArgs e)
{
// showing cell values in popUp here..
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('cell clicked')");
}
private DataTable getBindingData()
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("EmpName"));
dt.Columns.Add(new DataColumn("Monday"));
dt.Columns.Add(new DataColumn("TuesDay"));
dt.Columns.Add(new DataColumn("WednesDay"));
dt.Columns.Add(new DataColumn("ThursDay"));
dt.Rows.Add("EmpOne", "p", "p", "p", "a");
dt.Rows.Add("EmpTwo", "p", "a", "p", "p");
dt.Rows.Add("EmpThree", "p", "p", "p", "a");
dt.Rows.Add("EmpFour", "p", "a", "p", "p");
dt.Rows.Add("EmpFive", "p", "p", "p", "a");
dt.Rows.Add("EmpSix", "a", "p", "p", "p");
return dt;
}
}
and corresponding DynamicTemplate class is
public class DynamicTemplate : System.Web.UI.ITemplate
{
System.Web.UI.WebControls.ListItemType templateType;
System.Collections.Hashtable htControls = new System.Collections.Hashtable();
System.Collections.Hashtable htBindPropertiesNames = new System.Collections.Hashtable();
System.Collections.Hashtable htBindExpression = new System.Collections.Hashtable();
public DynamicTemplate(System.Web.UI.WebControls.ListItemType type)
{
templateType = type;
}
public void AddControl(WebControl wbControl, String BindPropertyName, String BindExpression)
{
htControls.Add(htControls.Count, wbControl);
htBindPropertiesNames.Add(htBindPropertiesNames.Count, BindPropertyName);
htBindExpression.Add(htBindExpression.Count, BindExpression);
}
public void InstantiateIn(System.Web.UI.Control container)
{
PlaceHolder ph = new PlaceHolder();
for (int i = 0; i < htControls.Count; i++)
{
//clone control
Control cntrl = CloneControl((Control)htControls[i]);
switch (templateType)
{
case ListItemType.Header:
break;
case ListItemType.Item:
ph.Controls.Add(cntrl);
break;
case ListItemType.AlternatingItem:
ph.Controls.Add(cntrl);
ph.DataBinding += new EventHandler(Item_DataBinding);
break;
case ListItemType.Footer:
break;
}
}
ph.DataBinding += new EventHandler(Item_DataBinding);
container.Controls.Add(ph);
}
public void Item_DataBinding(object sender, System.EventArgs e)
{
PlaceHolder ph = (PlaceHolder)sender;
GridViewRow ri = (GridViewRow)ph.NamingContainer;
for (int i = 0; i < htControls.Count; i++)
{
if (htBindPropertiesNames[i].ToString().Length > 0)
{
Control tmpCtrl = (Control)htControls[i];
String item1Value = (String)DataBinder.Eval(ri.DataItem, htBindExpression[i].ToString());
Control ctrl = ph.FindControl(tmpCtrl.ID);
Type t = ctrl.GetType();
System.Reflection.PropertyInfo pi = t.GetProperty(htBindPropertiesNames[i].ToString());
pi.SetValue(ctrl, item1Value.ToString(), null);
}
}
}
private Control CloneControl(System.Web.UI.Control src_ctl)
{
Type t = src_ctl.GetType();
Object obj = Activator.CreateInstance(t);
Control dst_ctl = (Control)obj;
PropertyDescriptorCollection src_pdc = TypeDescriptor.GetProperties(src_ctl);
PropertyDescriptorCollection dst_pdc = TypeDescriptor.GetProperties(dst_ctl);
for (int i = 0; i < src_pdc.Count; i++)
{
if (src_pdc[i].Attributes.Contains(DesignerSerializationVisibilityAttribute.Content))
{
object collection_val = src_pdc[i].GetValue(src_ctl);
if ((collection_val is IList) == true)
{
foreach (object child in (IList)collection_val)
{
Control new_child = CloneControl(child as Control);
object dst_collection_val = dst_pdc[i].GetValue(dst_ctl);
((IList)dst_collection_val).Add(new_child);
}
}
}
else
{
dst_pdc[src_pdc[i].Name].SetValue(dst_ctl, src_pdc[i].GetValue(src_ctl));
}
}
return dst_ctl;
}
}
Here the Data showing in gridview is fine. Here the Issues are when i click on the linkButton the page reloads and no grid is displaying after the postback.
second issue is, for LinkButton the Click Event is not firing.
Please provide me the help full information/Sample to show the modal window when we click on the linkButton of the gridview.
You need to use ajax model popup expender.
Design a panel with your fields and use the model popup expender to display that popup
This link has the sample of it
www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/modalpopup/modalpopup.aspx
and in your link button click
you have to use show method to open popup
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenateGridView();
}
this code is generating a gridview only if it is not a postback, but when you click a linkbutton a postpack occurs and that's the reason why gridview doesnt show again when you click on the linkbutton.
add the following code(additional else part included to your if code) to show gridview when you click lnkButton
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenateGridView();
else
{
string ctrlName = Request.Params.Get("__EVENTTARGET").Trim();
if (!String.IsNullOrEmpty(ctrlName))
{
if (ctrlName.StartsWith("lnkButton"))
{
GenateGridView();
}
}
}
}
It will be a good choice to use CommandName property for the linkbutton on the Gridview and give it a specfic name and in the code file and exactly work with it in RowCommand event of your GridView as following in this example :
first here is the .aspx file :
<div>
<asp:GridView ID="GridViewStudents" runat="server" AutoGenerateColumns="False" OnRowCommand="GridViewStudents_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Stud_ID" Visible="False">
<ItemTemplate>
<asp:Label ID="LabelStudID" runat="server" Text='<%# Eval("Stud_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FKFather_ID" Visible="False">
<ItemTemplate>
<asp:Label ID="LabelFkFatherID" runat="server" Text='<%# Eval("Fk_Father_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Name">
<ItemTemplate>
<asp:Label ID="LabelStudName" runat="server" Text='<%# Eval("Stud_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Class Name">
<ItemTemplate>
<asp:Label ID="LabelRowlevelName" runat="server" Text='<%# Eval("Stud_Level_Row_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="ImageButtonDelete" runat="server" CommandArgument='<%# Eval("Stud_ID") %>' CommandName="Remove" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div style="direction: ltr">
<asp:Panel ID="Panel1" runat="server" Visible="false">
<asp:Label ID="Labelpopupmessage" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="Buttonaccept" runat="server" Text="نعم" OnClick="Buttonaccept_Click" />
<asp:Button ID="Buttoncancel" runat="server" Text="لا" OnClick="Buttoncancel_Click" />
</asp:Panel>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:ModalPopupExtender runat="server" ID="ModalPopupExtenderStudent" PopupControlID="ButtonSubmit" TargetControlID="HiddenField1" CancelControlID="Buttoncancel">
</asp:ModalPopupExtender>
</div>
and here is the code implementation of my illustration :
protected void GridViewStudents_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Remove")
{
// I stored the ID of the selected Student I want to delete in a viewstate.
ViewState.Add("DeletedStudDetailID",Convert.ToInt32(e.CommandArgument));
ModalpopupExtender.Show();
}
}
// Here in the accept delete button I used that code ..
protected void Buttonaccept_Click(object sender, EventArgs e)
{
try
{
if (ViewState["DeletedStudDetailID"] != null)
{
StudentDetail StudDet = Data.StudentDetails.Single(SD => SD.Fk_Stud_ID == Convert.ToInt32(ViewState["DeletedStudDetailID"]));
Data.StudentDetails.DeleteOnSubmit(StudDet);
Student Stud = Data.Students.Single(S => S.Stud_ID == Convert.ToInt32(ViewState["DeletedStudDetailID"]));
Data.Students.DeleteOnSubmit(Stud);
Data.SubmitChanges();
}
this.ResultMessage = "Delete Done Sucessfully !!";
}
catch
{
this.ErrorMessage = "Delete operation disordered !!";
}
finally
{
ModalPopExtender.Hide();
}
}
I hope it helps in your issue and I wish you a happy day :) !!
First, your GridView will be created when calling GenateGridView method, so you have to call this method everytime you do post back, then your Page_Load should be
protected void Page_Load(object sender, EventArgs e)
{
GenateGridView();
}
Second, I would present you the other way to add LinkButton to GridView dynamically.
I modified your GenateGridView to just add only label into DynamicTemplate, also add this line gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(gvDynamicArticle_RowDataBound); to handle adding LinkButton.
private void GenateGridView()
{
TemplateField tempField;
DynamicTemplate dynTempItem;
Label label;
GridView gvDynamicArticle = new GridView();
gvDynamicArticle.Width = Unit.Pixel(500);
gvDynamicArticle.BorderWidth = Unit.Pixel(0);
gvDynamicArticle.Caption = "<div>Default Grid</div>";
gvDynamicArticle.AutoGenerateColumns = false;
gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(gvDynamicArticle_RowDataBound);
DataTable data = getBindingData();
for (int i = 0; i < data.Columns.Count; i++)
{
tempField = new TemplateField();
dynTempItem = new DynamicTemplate(ListItemType.AlternatingItem);
string ColumnValue = data.Columns[i].ColumnName;
tempField.HeaderText = ColumnValue;
label = new Label();
label.ID = string.Format("Label{0}", i);
dynTempItem.AddControl(label, "Text", ColumnValue);
label.Width = 100;
tempField.ItemTemplate = dynTempItem;
gvDynamicArticle.Columns.Add(tempField);
}
gvDynamicArticle.DataSource = data;
gvDynamicArticle.DataBind();
divContainer.Controls.Add(gvDynamicArticle);
}
I implement like this in RowDataBound event handler of the GridView to add LinkButton and hide the Label which we added it before:
protected void gvDynamicArticle_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int j = 1; j < e.Row.Cells.Count; j++)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkButton = new LinkButton();
lnkButton.ID = string.Format("lnkButton{0}{1}", e.Row.DataItemIndex, j);
lnkButton.Click += new EventHandler(lnkButton_Click);
Label tempLabel = e.Row.FindControl("Label" + j) as Label;
lnkButton.Text = tempLabel.Text;
lnkButton.CommandArgument = tempLabel.Text;
tempLabel.Visible = false;
e.Row.Cells[j].Controls.Add(lnkButton);
}
}
}
You can also set any value to CommandArgument of LinkButton, then you can show it in the alert.
Final, seems you want to show some value in the alert, you may code like this
public void lnkButton_Click(object sender, EventArgs e)
{
// showing cell values in popUp here..
LinkButton lnk = (LinkButton)sender;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('cell clicked, value " + lnk.CommandArgument + "')", true);
}

Telerik radgrid paging in webshop, breaks when changing product amount on last page

I'm having some problems with one of our webshops.
A Telerik radgrid works as the cart and lists all products currently in the cart.
The paging on the Radgrid correctly splits the cart view into different pages.
The problem occurs when one manually tries to change the amount of a product, but only if the product is on the LAST page of the radgrid and only if the number of products are less than the page size limit.
I can't post images yet, so have to give you a link.
Image link http://i.stack.imgur.com/hfFIx.jpg
I have figured it out as much as the radgrid believes there are always an even amount of products, based on the radgrid's page size.
The crash occurs in the tbQuantity_TextChanged event handler, more specific when var shopItemID = Convert.ToInt32(item.GetDataKeyValue("ID")); is called for an item that doesn't exist on this page, but on another page.
The exception is
System.ArgumentOutOfRangeException was unhandled by user code
Message=Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Gridview code
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ShopItems.ascx.cs" Inherits="Litho.Framework.Web.Modules.Shop.ShopItems" %>
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<telerik:RadGrid
ID="gvCartItems"
runat="server"
AutoGenerateColumns="False"
AllowPaging="True"
PageSize="5"
Skin="Default"
GridLines="None"
AllowFilteringByColumn="False"
AllowSorting="True"
ShowFooter="True"
OnNeedDataSource="gvCartItems_NeedDataSource"
OnItemCreated="gvCartItems_ItemCreated"
OnItemDataBound="gvCartItems_ItemDataBound"
OnDeleteCommand="gvCartItems_DeleteCommand">
<MasterTableView Width="100%" NoMasterRecordsText="Inga artiklar" ShowHeadersWhenNoRecords="false" DataKeyNames="ID">
<Columns>
<telerik:GridButtonColumn ButtonType="ImageButton" CommandName="Delete" Text="Radera" UniqueName="DeleteColumn" HeaderStyle-Width="20" />
<telerik:GridTemplateColumn HeaderText="Antal" HeaderStyle-Width="110px" DataField="Quantity" UniqueName="Quantity" Aggregate="Sum" FooterText="Totalt antal: ">
<ItemTemplate>
<telerik:RadNumericTextBox
ID="tbQuantity"
runat="server"
AutoPostBack="true"
Width="70px"
MinValue="1"
Visible="false"
ShowSpinButtons="true"
IncrementSettings-InterceptArrowKeys="false"
NumberFormat-GroupSizes="9"
NumberFormat-DecimalDigits="0"
IncrementSettings-InterceptMouseWheel="true"
NumberFormat-AllowRounding="False"
OnTextChanged="tbQuantity_TextChanged">
<EnabledStyle HorizontalAlign="Right" />
</telerik:RadNumericTextBox>
<telerik:RadComboBox ID="ddlQuantity" DataTextField="Quantity" DataValueField="Quantity" Visible="false" runat="server" Width="50px" AutoPostBack="true" OnSelectedIndexChanged="ddlQuantity_SelectedIndexChanged" />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn HeaderText="Artnr" ReadOnly="True" DataField="ArticleNumber" UniqueName="ArticleNumber" HeaderStyle-Width="80" />
<telerik:GridTemplateColumn HeaderText="Artikel" UniqueName="Title" ShowFilterIcon="false">
<ItemTemplate>
<asp:HyperLink ID="hlTitle" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="a`pris" UniqueName="Price" ShowFilterIcon="false">
<ItemTemplate>
<asp:Label ID="lblUnitprice" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Totalpris" UniqueName="Totalprice" ShowFilterIcon="false">
<ItemTemplate>
<asp:Label ID="lblTotalPrice" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
<FooterStyle Font-Bold="true" BackColor="#e6e6e6" />
<PagerStyle Mode="NextPrevAndNumeric" />
<FilterMenu EnableTheming="True">
<CollapseAnimation Duration="200" Type="OutQuint" />
</FilterMenu>
</telerik:RadGrid>
<asp:PlaceHolder ID="phItemSummary" runat="server" />
Code behind
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Litho.Framework.BusinessLayer;
using Litho.Framework.BusinessLayer.Base;
using Litho.Framework.BusinessLayer.Base.Settings;
using Litho.Framework.BusinessLayer.Modules.Shop;
using Litho.Framework.PresentationLayer;
using Litho.Framework.ServiceLayer;
using Telerik.Web.UI;
namespace Litho.Framework.Web.Modules.Shop
{
public partial class ShopItems : UserControl
{
IShopItemHolder _shopItemHolder = null;
bool _readMode = true;
SessionHelper _sessionHelper = new SessionHelper();
#region Public methods
public void LoadItems(IShopItemHolder shopItemHolder, bool readMode)
{
_shopItemHolder = shopItemHolder;
_readMode = readMode;
gvCartItems.Rebind();
loadItemsSummary();
}
private void loadItemsSummary()
{
phItemSummary.Controls.Clear();
var ucItemSummary = (ShopItemsSummary)Page.LoadControl("~/Modules/Shop/ShopItemsSummary.ascx");
ucItemSummary.LoadItemSummary(_shopItemHolder);
phItemSummary.Controls.Add(ucItemSummary);
}
#endregion
#region Events
protected void gvCartItems_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
gvCartItems.DataSource = _shopItemHolder.Items;
}
protected void gvCartItems_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
var item = (GridDataItem)e.Item;
var btnDelete = (ImageButton)item["DeleteColumn"].Controls[0];
btnDelete.ImageUrl = string.Format("~/Base/Themes/{0}/Images/Icons16x16/iconDelete.png", SettingsManager.GetGlobalSettings().AdminTheme);
btnDelete.Visible = !_readMode;
}
}
protected void gvCartItems_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
var shopItem = (IShopItem)e.Item.DataItem;
var hlTitle = (HyperLink)e.Item.FindControl("hlTitle");
var lblUnitPrice = (Label)e.Item.FindControl("lblUnitprice");
var lblTotalPrice = (Label)e.Item.FindControl("lblTotalPrice");
if (!shopItem.IsExternal)
{
var tbQuantity = (RadNumericTextBox)e.Item.FindControl("tbQuantity");
tbQuantity.ShowSpinButtons = !_readMode;
tbQuantity.Text = shopItem.Quantity.ToString();
tbQuantity.Visible = true;
tbQuantity.Enabled = !_readMode;
}
else
{
if (!_readMode)
{
var ddlQuantity = (RadComboBox)e.Item.FindControl("ddlQuantity");
ddlQuantity.DataSource = shopItem.PriceCollection;
ddlQuantity.DataBind();
ddlQuantity.SelectedValue = shopItem.Quantity.ToString();
ddlQuantity.Visible = true;
}
}
if (!shopItem.IsExternal)
{
var parameters = new Dictionary<string, string>();
parameters.Add(KeyMaster.RequestParamsNames.Modules.Shop.PRODUCT_ID, shopItem.ID.ToString());
hlTitle.NavigateUrl = new FWContent().GetContentUrl(ModuleIDConstant.SHOP, ContentIDConstant.Shop.PRODUCT_VIEW, parameters);
}
hlTitle.Text = shopItem.Title;
lblUnitPrice.Text = shopItem.Price.ToString("0.00") + " SEK";
lblTotalPrice.Text = shopItem.GetCost(false).ToString("0.00") + " SEK";
}
}
protected void tbQuantity_TextChanged(object sender, EventArgs e)
{
if (!_readMode)
{
RadNumericTextBox tbQuantity;
foreach (GridDataItem item in gvCartItems.Items)
{
if (item is GridDataItem)
{
tbQuantity = item.FindControl("tbQuantity") as RadNumericTextBox;
var shopItemID = Convert.ToInt32(item.GetDataKeyValue("ID"));
var shopItem = _sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID);
if (!shopItem.IsExternal)
{
_sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID).Quantity = Convert.ToInt32(tbQuantity.Text);
_sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID).TotalPrice = _sessionHelper.CurrentCart.GetItemCost(shopItemID, false);
_shopItemHolder = _sessionHelper.CurrentCart;
}
}
}
loadItemsSummary();
gvCartItems.Rebind();
}
}
protected void gvCartItems_DeleteCommand(object source, GridCommandEventArgs e)
{
if (!_readMode)
{
var cartItemID = (int)e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"];
_sessionHelper.CurrentCart.DeleteItem(cartItemID);
_shopItemHolder = _sessionHelper.CurrentCart;
if (_sessionHelper.CurrentCart.Items.Count == 0)
{
Response.Redirect(new FWContent().GetContentUrl(ModuleIDConstant.SHOP, ContentIDConstant.Shop.CART));
}
else
{
gvCartItems.Rebind();
loadItemsSummary();
}
}
}
protected void ddlQuantity_SelectedIndexChanged(object sender, EventArgs e)
{
RadComboBox ddlQuantity;
foreach (GridDataItem item in gvCartItems.Items)
{
if (item is GridDataItem)
{
ddlQuantity = item.FindControl("ddlQuantity") as RadComboBox;
var cartItemID = Convert.ToInt32(item.GetDataKeyValue("ID"));
var cartItem = _sessionHelper.CurrentCart.CartItems.Find(x => x.ID == cartItemID);
if (cartItem.IsExternal)
{
cartItem.Quantity = Convert.ToInt32(ddlQuantity.Text);
cartItem.TotalPrice = getProductPrice(cartItem);
}
}
}
loadItemsSummary();
gvCartItems.Rebind();
}
#endregion
private double getProductPrice(CartItem cartitem)
{
foreach (var price in cartitem.PriceCollection)
{
if (price.Quantity == cartitem.Quantity)
{
return price.Price;
}
}
throw new Exception(); // todo lägg till customexception
}
}
}
Thanks in advance!
Edit:
Small update, I've been trying to work something out with CustomPaging, but no luck so I am still using the posted code as it is.
I find it strange that the paging works as it should now, it is just when I change amount on the last page that it crashes.
The guys at Telerik helped me, the problem was that I was going through all items and not just the one where the amount changed.
Updated tbQuantity_TextChanged
protected void tbQuantity_TextChanged(object sender, EventArgs e)
{
if (!_readMode)
{
RadNumericTextBox tbQuantity = (RadNumericTextBox)sender;
GridDataItem dataItem = (GridDataItem)tbQuantity.NamingContainer;
var shopItemID = (int)dataItem.GetDataKeyValue("ID");
var shopItem = _sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID);
if (!shopItem.IsExternal)
{
_sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID).Quantity = Convert.ToInt32(tbQuantity.Text);
_sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID).TotalPrice = _sessionHelper.CurrentCart.GetItemCost(shopItemID, false);
_shopItemHolder = _sessionHelper.CurrentCart;
}
loadItemsSummary();
gvCartItems.Rebind();
}
}

Delete row from asp gridview via a LinkButton

I have been spending quite long time on research how to do this but had no luck.
<asp:GridView runat="server" ID="TBDSPCGrid"
AutoGenerateColumns="false"
AllowPaging="true"
AllowSorting="false"
DataKeyNames="SPID,CategoryId,Category,RowNum, PurchaseDate, Title, Description,SFItemId"
OnRowDataBound="TBDSPC_RowDataBound"
OnRowCreated="TBDSPC_RowCreated"
OnRowCommand="TBDSPC_Command"
OnPageIndexChanging="TBDSPC_PageIndexChanging"
OnRowDeleting="TBDSPC_OnRowDeleting">
<Columns>
<asp:TemplateField HeaderText="Timeouts" ItemStyle-Width="40px" ItemStyle-Wrap="false"
ItemStyle-CssClass="padding-right">
<ItemTemplate>
<div class="targeted-icons">
<asp:LinkButton runat="server" id="LinkButton1" CommandName="delete" CommandArgument='<%#Eval("SFItemId")%>'
><img src="delete.png" /></asp:LinkButton>
</div>
</ItemTemplate>
</asp:TemplateField>
So what should I do here?
protected void TBDSPCGrid_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
// do something
}
I tried this but it is not working...it gave me an error of "object reference not set to an instance of an object"
protected void TBDSPC_Command(object sender, GridViewCommandEventArgs e)
{
GridView gv = (GridView)sender;
switch (e.CommandName)
{
case "delete":
{
DataTable test = TargetedSpView.ToTable();
test.Rows[0].Delete();
test.AcceptChanges();
TargetedSpView = test.DefaultView;
this.TBDSPCGrid.DataSource = this.TargetedSpView;
this.TBDSPCGrid.DataBind();
}
break;
}
}
protected void TBDSPC_Command(object sender, GridViewCommandEventArgs e)
{
GridView gv = (GridView)sender;
switch (e.CommandName)
{
case "delete":
{
DataTable test = RetrieveData(0, 0); // this is a function I used to get a datatable
test.Rows[0].Delete();
test.AcceptChanges();
TargetedSpView = test.DefaultView;
TBDSPCGrid.DataSource = TargetedSpView;
TBDSPCGrid.DataBind();
}
break;
}
}

Categories