Trying to convert functional asp:CommandField to asp:LinkButton via asp:TemplateField - asp.net

I want to take advantage of the breadth of attributes available to a LinkButton compared to a CommandField. When calling the code behind method from on click I get this error message:
CS0123: No overload for 'ViewHandler' matches delegate
'System.EventHandler'.
GridView definition:
<asp:GridView ID="wc" EmptyDataText="Empty WC table..." runat="server"
AutoGenerateColumns="False" GridLines="Horizontal" DataKeyNames="WC_ID,PW_ID,R_Qty"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"
AllowSorting="true" OnSorting="Sorting" AllowPaging="true" PageSize="15" ViewStateMode="Enabled"
OnSelectedIndexChanging="ViewHandler" OnPageIndexChanging="HandlePageIndexChanging" OnRowDataBound="gvRowDataBound"
OnRowEditing="gvRowEditing" OnRowCancelingEdit="gvRowCancelingEdit" OnRowUpdating="gvRowUpdating">
Orig button...
<asp:CommandField ControlStyle-Font-Size="Smaller" ControlStyle-ForeColor="#717171" HeaderText="..." ShowSelectButton="True" ItemStyle-HorizontalAlign="Center" SelectText="..." />
Convert to....
<asp:TemplateField HeaderText="..." ShowHeader="True" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton style="font-size: 0.9em; color: #717171" ID="Details" runat="server" CausesValidation="False" OnClick="ViewHandler" CommandName="ViewHandler" Text="..." ToolTip="Click here to see purchase history and notes"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Code behind:
protected void ViewHandler(object sender, GridViewSelectEventArgs e)
{
string WC_ID =wc.Rows[e.NewSelectedIndex].Cells[0].Text;
string PW_ID = wc.Rows[e.NewSelectedIndex].Cells[1].Text;
string VIN = wc.Rows[e.NewSelectedIndex].Cells[2].Text;
string PROD = wc.Rows[e.NewSelectedIndex].Cells[3].Text;
string W = wc.Rows[e.NewSelectedIndex].Cells[4].Text;
string SIZE = wc.Rows[e.NewSelectedIndex].Cells[5].Text;
e.Cancel = true;
Session.Add(WebConstants.WC_ID, WC_ID);
Session.Add(WebConstants.PW_ID, PW_ID);
Session.Add(WebConstants.VIN, VIN);
Session.Add(WebConstants.PROD, PROD);
Session.Add(WebConstants.W, W);
Session.Add(WebConstants.SIZE, SIZE);
DetailsNavigateMethod.DynamicInvoke();
HandlePageNavigation(WebConstants.WC_DETAILS, "WC View for WC_PurchaseID-> " + Session[WebConstants.WC_ID].ToString());
}
What do I need to do to make the signature match with the ViewHandler method? I did notice if I switch from GridViewSelectEventArgs to EventArgs the overload error goes away but then e.NewSelectedIndex does not exists...
Thanks!

Your problem is that the OnClick event handler for a LinkButton must have this signature:
protected void LinkButton_Click(Object sender, EventArgs e)
But you are defining it as
protected void ViewHandler(object sender, GridViewSelectEventArgs e)
However, you won't have access to e.NewSelectedIndex, obviously. What you can do is change your markup to (notice the CommandArgument part):
<asp:TemplateField HeaderText="..." ShowHeader="True" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton style="font-size: 0.9em; color: #717171" ID="Details" runat="server" CausesValidation="False" OnClick="ViewHandler" CommandName="ViewHandler" CommandArgument='<%=string.Format("{0},{1},{2},{3}",Eval("Prop1"),Eval("Prop2"),Eval("Prop3"),Eval("Prop4")) %>' Text="..." ToolTip="Click here to see purchase history and notes"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
And your code to:
protected void LinkButton_Click(Object sender, EventArgs e)
{
string [] values = ((LinkButton)(sender)).CommandArgument.Split(new char[]{','});
//where values[0] will have WC_ID, values[1]=PW_ID, etc,
Session.Add(WebConstants.WC_ID, values[0]);
Session.Add(WebConstants.PW_ID, values[1]);//etc...
//Session.Add(WebConstants.VIN, VIN);
//Session.Add(WebConstants.PROD, PROD);
//Session.Add(WebConstants.W, W);
//Session.Add(WebConstants.SIZE, SIZE);
DetailsNavigateMethod.DynamicInvoke();
HandlePageNavigation(WebConstants.WC_DETAILS, "WC View for WC_PurchaseID-> " + Session[WebConstants.WC_ID].ToString());
}
Note:
Prop1, Prop2, etc. have to be changed to actual property names from your data source.
Above code hasn't been tested but that's the idea.

Related

Unable to get selected item of dx:ASPxListBox on ASPxGridView_Updating event of devexpress control

I have used dx:ASPxGridView where I have one dx:GridViewDataTextColumn with EditItemTemplate which contain dx:ASPxListBox. When I click on update command I am not able to get selected items of dx:ASPxListBox under ASPxGridView_Updating.
<dx:ASPxGridView
ID="ASPxGridView"
runat="server"
AutoGenerateColumns="False"
DataSourceID="TradersDS"
KeyFieldName="TraderId">
<SettingsEditing Mode="PopupEditForm" PopupEditFormWidth="600px" />
<ClientSideEvents RowDblClick="function(s, e)
{
s.StartEditRow(e.visibleIndex);
}"
EndCallback="PrepareGridViewForNewDesing" Init="PrepareGridViewForNewDesing" />
<Columns>
....
<dx:GridViewDataTextColumn FieldName="CounterParty" VisibleIndex="3">
<EditItemTemplate>
<dx:ASPxListBox ID="lstCounterParty" runat="server" SelectionMode="CheckColumn" EnableSelectAll="true"
Width="285"
Height="300"
DataSourceID="CounterPartiesDS"
ValueField="ID"
ValueType="System.String"
TextField="Name">
<%-- <ClientSideEvents SelectedIndexChanged="function(s, e) {lbModels.PerformCallback('1');}" />--%>
</dx:ASPxListBox>
</EditItemTemplate>
</dx:GridViewDataTextColumn>
...
</Columns>
</dx:ASPxGridView>
C# Code..
protected override void ASPxGridView_Updating(object sender, ASPxDataUpdatingEventArgs e)
{
var gridView = sender as ASPxGridView;
GridViewDataColumn list = gridView.Columns["CounterParty"] as GridViewDataColumn;
var counterPartyListBox = (ASPxListBox)gridView.FindEditRowCellTemplateControl(list, "lstCounterParty");
string selectedItemsAsString = string.Empty;
foreach (ListEditItem item in counterPartyListBox.SelectedItems)
selectedItemsAsString += item.Value + ";";
base.ASPxGridView_Updating(sender, e);
}
Here I always get count 0 of SelectedItems. On addition to this My devExpress control version are 9.3.3
What is wrong with this code any help , guidance really appreciated.
Make sure that you set the ASPxListBox.ValueType property to the corresponding .NET type that matches the type of the "ValueField" column.
May be, according to the (ValueField="ID"), the (ASPxListBox.ValueType) should be numeric? (System.Int32, etc.)

Remove TemplateField during page load or before databind

I want to remove templatefield from gridview during pageload or before databind to GridView. I have 2 data sources for retrieving data. The data retrieved from one of the data sources do not have the columns ExpireDate and ExpireDays.
So I want to delete the templatefields corresponding to ExpireDate and ExpireDays if the GridView is populated from the data source that do not have those 2 fields.
Setting the visibility to false still will have error of DataRowView doesn't contain property name ExpireDate and ExpireDays.
Markup
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" HeaderText="No."/>
<asp:BoundField DataField="Name" HeaderText="Name"/>
<asp:BoundField DataField="CourseName" HeaderText="Course Enroll" />
<asp:BoundField DataField="SubMember" HeaderText="ChildMember" />
<asp:TemplateField HeaderText="Expiry Days">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label runat="server" ID="expDsL" Text=' <%# Eval("ExpiryDays") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expiry On">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label runat="server" ID="expDeL" Text=' <%# Eval("ExpiryDate") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Function">
<ItemStyle HorizontalAlign="Center" Width="100px"></ItemStyle>
<ItemTemplate>
<asp:ImageButton ImageUrl="~/Images/editB.gif" ID="btnEdit" runat="server" ToolTip="Edit" CommandName="Edit" CommandArgument='<%# Eval("ID") %>' />
<asp:ImageButton ImageUrl="~/Images/delB.gif" ID="btnDelete" runat="server" ToolTip="Delete" CommandName="Delete" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if(Class.ToLower() != "classAA")
{
// using naveen answer can remove the column.
var expiryDateF = ((DataControlField)GridView1.Columns.Cast<DataControlField>().Where(fid => fid.HeaderText == "Expiry Days").SingleOrDefault());
var expiryDaysF = ((DataControlField)GridView1.Columns.Cast<DataControlField>().Where(fid => fid.HeaderText == "Expiry On").SingleOrDefault());
if (expiryDateF != null)
{
GridView1.Columns.Remove(expiryDateF);
}
if (expiryDaysF != null)
{
GridView1.Columns.Remove(expiryDaysF);
}
}
if(!this.IsPostBack)
{
BindData();
}
}
protected void SaveMember(object sender, EventArgs e)
{
//getting member information and perform checking.
bool success = dbbb.AddMem(memberdetails);
if(success == true)
{
BindData();
}
else
{
//prompt fail message.
}
}
protected void BindData()
{
DataTable dt = dbbb.RetrieveList();
if(dt != null)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton btnDel = (ImageButton)e.Row.FindControl("btnDelete");
btnDel.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this member?')");
}
}
How could I delete the column?
Two methods to achieve this
Method 1 - Remove by Index
if(!table.Columns.Contains("CustomerID1"))
{
//seven is the column index here. ie, 8th column
CustomersGrid.Columns.RemoveAt(7);
}
Method 2 - Remove using Columns Header Text
var expiryDateField= ((DataControlField)CustomersGrid.Columns
.Cast<DataControlField>()
.Where(fld => fld.HeaderText == "Expiry Date")
.SingleOrDefault());
if(expiryDateField != null)
{
CustomersGrid.Columns.Remove(expiryDateField);
}
Please not that
CustomersGrid is the name of the asp:GridView here.
table is the DataTable that acts as the DataSource of the GridView
The code should be called before DataBind of the GridView
Attach to the rowDataBound event of the grid, there you can set it dynamically.
You have to know the datasource name of the field you want to hide,
for example the headertext for the cell is "SomeHeader", but the databoundfield name for that cell is
"SomeOtherName"
then you have to check it like this (debug through GetColumnIndexByName) and
check the value of
((BoundField)cell.ContainingField).DataField
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
break;
columnIndex++; // keep adding 1 while we don't have the correct name
}
return columnIndex;
}
remember that the code above will use a BoundField... then use it like:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "SomeOtherName");
string columnValue = e.Row.Cells[index].Text;
}
}

Getting row from hyperlink in Gridview

I have a Hyperlink field in a asp.net gridview that runs code behind in an aspx file, like
<asp:GridView ID="gvCoursesList" runat="server">
<Columns>
<asp:BoundField DataField="Course" HeaderText="Course">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lblSignup" runat="server" Text="Sign Up" OnClick= "lblSignup_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In my code behind file I have the function:
protected void lblSignup_Click(object sender, EventArgs e)
{
}
How do I retrieve the value of the first column from this function.
I would like to do something like
string course = gvCoursesList.DataKeys[e.RowIndex].Value.ToString();
but it's not working. Any other ideas?
#jishnusaha should be the approach you should take. Here is another alternative: http://forums.asp.net/p/1137287/1821091.aspx
protected void lblSignup_Click(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
GridViewRow row = btn.NamingContainer as GridViewRow;
string course = gvCoursesList.DataKeys[row.RowIndex].Value.ToString();
}
<asp:GridView ID="gvCoursesList" runat="server" OnRowCommand="gvCoursesList_RowCommand">
<Columns>
<asp:BoundField DataField="Course" HeaderText="Course">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lblSignup" runat="server" Text="Sign Up" CommandName="SignUp" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void gvCoursesList_RowCommand(object sender, GridViewRowCommandEventArgs e)
{
if(e.CommandName=="SignUp")
{
string course = gvCoursesList.DataKeys[e.RowIndex].Value.ToString();
}
}
Use the .cells.text to get the value out:
protected void lblSignup_Click(object sender, EventArgs e)
{
GridViewRow row = gvCoursesList.rows[e.rowindex]
string course = row.cells[cellIndex].text;
}
With thanks to codingbiz. His solution just needed a little tweak as per below.
LinkButton btn = sender as LinkButton;
GridViewRow row = btn.NamingContainer as GridViewRow;
string course = row.Cells[0].Text;

Radio list with SelectedIndexChanged not firing inside radgrid

I have a user control that contains a radio list that on SelectIndexChanged it updates a drop down.
I put together a basic page and add the user control to the page it works fine but when I move the control to inside a radgrid it doesn't work, it will post back but never call the SelectIndexChanged event.
I've pulled up 2 previous questions on this Q. 1 and Q. 2 which say that OnSelectedIndexChanged needed to be set in the aspx page. My issue is that the control doesn't exist in the aspx page and is created later so that solution does not work for me.
Working code
working.aspx
<TT:ToolTipControl ID="ToolTipEdit" runat="server" />
working.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
ToolTipEdit.getEditToolTip("POL_TERM_CD", "DataPolTermDropDownlistEdit");
}
User Control
userControl.ascx.cs
public void getEditToolTip(string fieldName, string ddlName)
{
DataPolTermRadioListBox ccPolTermRadioListBox = new DataPolTermRadioListBox(); //custom radio list
ccPolTermRadioListBox.ID = "PolTermRadioListBox";
ccPolTermRadioListBox.AutoPostBack = true;
ccPolTermRadioListBox.SelectedIndexChanged += new System.EventHandler(updateParent);
ToolTip.Controls.Add(ccPolTermRadioListBox);
}
Broken Code
brokenPage.aspx
<telerik:RadGrid ID="rgState" Skin="WebBlue" runat="server" OnNeedDataSource="rgState_NeedDataSource"
AutoGenerateColumns="False" OnPreRender="rgState_PreRender">
<MasterTableView DataKeyNames="wrtnStPolId" AllowAutomaticUpdates="false" AllowAutomaticDeletes="true"
AllowAutomaticInserts="false" CommandItemDisplay="Top" AllowMultiColumnSorting="True"
EditMode="InPlace" GroupLoadMode="Server" Caption="State(s) and Exposure(s)">
<Columns>
<telerik:GridTemplateColumn AllowFiltering="false" HeaderText="Pol Type Nstd" SortExpression="nonStdPolTypeCd"
UniqueName="nonStdPolTypeCd">
<ItemTemplate>
<asp:Label ID="lblNonStdPolTypeCd" runat="server" align="center" Text='<%#DataBinder.Eval(Container.DataItem, "nonStdPolTypeCd")%>' />
</ItemTemplate>
<EditItemTemplate>
<cc1:DataNonStdTypeCdDropDownList ID="ddlNonStdTypeCd" runat="server" ClientIDMode="Predictable">
</cc1:DataNonStdTypeCdDropDownList>
<TT:ToolTipControl ID="ttcNonStdPolTypeCdEdit" runat="server" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
brokenPage.aspx.cs
protected void rgState_PreRender(object sender, EventArgs e)
{
RadGrid rgExpMod = (RadGrid)sender;
foreach (GridDataItem row in rgExpMod.Items)
{
GridDataItem gdiItem = (GridDataItem)row;
if (row.FindControl("ttcNonStdPolTypeCdEdit") != null)
{
DropDownList ddl = (DropDownList)row.FindControl("ddlNonStdTypeCd");
ddl.ID += row.RowIndex;
ddl.SelectedIndex = 2;
NCCI.PDC.Web.Controls.ucToolTip ttcNonStdPolTypeCdEdit = (NCCI.PDC.Web.Controls.ucToolTip)row.FindControl("ttcNonStdPolTypeCdEdit");
ttcNonStdPolTypeCdEdit.getEditToolTip("non_std_pol_type_cd", ddl.ID);
}
}
}

gridview edit requires to click twice

Why is that I need to click the edit link twice, in a gridview control, before my row enters into edit mode?
<asp:ObjectDataSource ID="ods" runat="server" TypeName="Employee"
SelectMethod="GetAll" ></asp:ObjectDataSource>
<asp:GridView ID="GridView1" runat="server" CssClass="styled"
OnRowCommand="gv_RowCommand" DataSourceID="ods"
OnSorting="gv_Sorting" >
<Columns>
...........
</Columns>
<ItemTemplate>
<ItemTemplate>
<div class='actions'>
<asp:Button ID="btnEdit" runat="server" Text=" Edit " ToolTip="Edit Row" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"Id") %>' CausesValidation="False" />
<span style="padding-left:10px"></span>
</div>
</ItemTemplate>
</asp:GridView>
protected override void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.ods.SelectParameters[0].DefaultValue = "";
}
}
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == CRUID.Edit.ToString())
{
this.gv.ShowFooter = false;
}
}
You need to avoid rebinding your gridview on each postback.
If not ispostback then
GridView1.DataSource = dt
GridView1.DataBind()
end if
Otherwise you just overwrite Gridview changes.
Great explanation at this link...
http://www.pcreview.co.uk/forums/gridview-two-clicks-needed-enter-place-editing-t3328887.html
Try handling the RowEditing event to set the EditItem Index:
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex
}
There are some mistakes in your code as i examined. Correct your code as shown below:
<asp:ObjectDataSource ID="ods" runat="server" TypeName="Employee"
SelectMethod="GetAll" ></asp:ObjectDataSource>
<asp:GridView ID="GridView1" runat="server" CssClass="styled"
OnRowCommand="gv_RowCommand" DataSourceID="ods"
OnSorting="gv_Sorting" >
<Columns>
...........
<asp:TemplateField>
<ItemTemplate>
<div class='actions'>
<asp:Button ID="btnEdit" runat="server" Text=" Edit " ToolTip="Edit Row" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"Id") %>' CausesValidation="False" />
<span style="padding-left:10px"></span>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected override void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.ods.SelectParameters[0].DefaultValue = "";
}
}
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
this.gv.ShowFooter = false;
}
}
If on using this code the problem does not solve then there may be some problem in your cssclass which you used with your GridView as I have Checked your code on my machine using ObjectDataSource and it works well using edited code.
Also I want to know that what is CRUID in CRUID.Edit.ToString()
and why you used the following line in Page_Load event
this.ods.SelectParameters[0].DefaultValue = "";
as there are no parameter associated with your SelectMethod="GetAll" method used in ObjectDataSource.
May this answer help you.
I guess there is some conflict with the updatepanels on your page..
Try removing all your Update Panels and try again.. It will work for sure.. Mine worked a few seconds ago.. so thought It would be good to share..

Resources