How can I disable/hide edit button in gridview control of ASP.net - asp.net

I have a gridview control in which there are two command buttons (linkButton), one is "select" and the other is "edit", now I have a session variable named as department and it contains values like "WRITING", "EDITING", "ADMIN" etc... Now the thing is I want the edit button to disappear when the department is "WRITING" but when it is "EDITING" or "ADMIN" I want edit button appear.
I was searching some forums for this problem and found this
row.Cells[0].Controls.Clear();
The problem with this code is that it hides the entire command column including "select" and "edit" buttons while I only want to control "edit" button, select should remain visible for all departments.
if I do it like (on row data bound event)
e.row.Cells[0].Controls[1].visible = false OR
e.row.Cells[0].Controls[0].visible = false
Specified argument was out of the range of valid values.
How can I do this properly ?
Thanks.

You can use the Visible property in the following way.
if (Session(mode) == "WRITING")
{
(e.Row.FindControl("btnEdit")).Visible = false;
}

First of all - your code does not work because your gridViewCell at index 0 contains only one control. Every CommandButton gets a single cell! Furthermore I am not quite sure why you make use of the RowDataBound event. As you are using a Session-Var this one may not change while binding your rows.
I tried the following piece of code in my pageLoad eventHandler - and it worked out for me:
/// just replace CAPITAL letters with your names and
/// (Session["department"] == "WRITING") with your boolean expression
gvYOURGV.Columns[INDEXOFSELECTCOLUMN].Visible = (Session["department"] == "WRITING");
In case you do want to have (need to have?) more flexibilty on modifying the appearance of your command columns - you may even consider, changing your command columns to templated columns. Doing so you may have the possibility for this code:
<asp:GridView ID="gvYOURGV" runat="server">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1"
visible='<%# Session["department"] != "WRITING" %>'
runat="server" CausesValidation="False"
CommandName="Select" Text="Auswählen"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
hth

Related

How do I set the Selected Value of a DropDownList inside an EditItemTemplate inside a DetailsView using the codebehind?

I have a Details View on my ASP.NET (VB) page which lists the details of a customer (their name, address, etc).
The 'Country' option is a drop down list, pulled from a database table. This all works fine when viewing the Details View and you can see what country they are in.
However, when I click the Edit button on the DetailsView, the drop down list then shows all the available countries in the db table correctly but it has no selected value, so instead of selecting their currently-set country, it just defaults to the top one in the list. This is wrong as it's not their currently-set value.
Using the codebehind (VB), how should I set the selected value of the dropdown list to be the country name that they currently have set? In the codebehind, I have already read their current country name in and stored it in a string variable called strCurrentCountryName
eg.
Response.Write "strCurrentCountryName: " & strCurrentCountryName
Will show:
strCurrentCountryName: United Kingdom
So I now need to match their strCurrentCountryName value with one of the country names in the drop down list and set this as the SelectedValue for them.
My code in front (which lists all the countries in the db):
<asp:TemplateField HeaderText="Country" SortExpression="address5">
<EditItemTemplate>
<asp:SqlDataSource ID="SqlDataSourcecountryList" runat="server" ConnectionString="<%$ ConnectionStrings:PDConnectionString %>"
ProviderName="<%$ ConnectionStrings:PDConnectionString.ProviderName %>"
SelectCommand="SELECT country_name_short, country_name_long FROM country_list WHERE deleted = 0 ORDER BY country_name_long">
</asp:SqlDataSource>
<asp:DropDownList ID="DropDownListCountry" runat="server" CssClass="form-control"
DataSourceID="SqlDataSourcecountryList" DataTextField="country_name_long" DataValueField="country_name_short">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("address5") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
In the codebehind, I tried this (inside the Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load):
DropDownListCountry.DataBind()
DropDownListCountry.Items.FindByText(strCurrentCountryName).Selected = True
Which gives an error message of:
'DropDownListCountry' is not declared. It may be inaccessible due to its protection level
I tried using these two lines of code with the drop down list placed OUTSIDE of the EditItemTemplate and it works perfectly:
DropDownListCountry.DataBind()
DropDownListCountry.Items.FindByText(strCurrentCountryName).Selected = True
Sure enough, it does then correctly set their Selected Value to be the correct country.
In my codebehind (vb), do I need to somehow declare the DropDownListCountry first?
How do I make this work when placed inside the EditItemTemplate of my asp:TemplateField ?
Since the drop down is inside the template, it is not statically declared anywhere in the page's code, and so there is no way to reference it directly by just DropDownListCountry. Consider this - if that was possible, and you had a grid view template with these, drop down in which row would you be referencing?
So in reality this drop down gets assigned a different ID based on the container template it is in. So you need to find it inside the template on data binding time and then set the selected value the way you did:
Dim ddl As DropDownList = CType(detailsViewId.FindControl("DropDownListCountry"), DropDownList)
ddl.Items.FindByText(strCurrentCountryName).Selected = True
Important thing is to make sure that this code is run once drop down control was created. Most suitable place is right after data binding happend. To do so, subscribe to the DataBound event:
<asp:DropDownList ID="DropDownList1" runat="server" OnDataBound="DropDownList1_DataBound">
and run the code inside the event handler:
Protected Sub DropDownList1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)
' Code above goes here
End Sub

drop down list in grdiview header and rowdatabound column change

i have a gridview that contains databound columns. two columns contain information that needs to be adjusted in the rowdatabound e.g if the cell in the column contains a 2 then change it to display 'code'.
i have done this before, however, now i have a drop down list to add to the gridview header, and the list items of the drop down will be 'all', 'uncode', 'code', now that i have put the drop down list in the header, when the grdiview populates it no longer changes the value '2' to say 'code', it keeps it as '2'. Can anyone shed some light in how i can get it to change back to 'code'
here is the code for the gridview item header/databind
<asp:TemplateField SortExpression ="true">
<HeaderTemplate>
Coding Stage
<asp:DropDownList ID ="ddlCoded" runat="server" OnSelectedIndexChanged="CodedChanged" AutoPostBack="true" AppendDataBoundItems ="true">
<asp:ListItem Text="ALL" Value="ALL"></asp:ListItem>
<asp:ListItem Text="uncode" Value="uncode"></asp:ListItem>
<asp:ListItem Text="code" Value="code"></asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<%#Eval("codingStage")%>
</ItemTemplate>
</asp:TemplateField>
if you need anymore information then please contact me and i will be happy to provide
markup:
<ItemTemplate>
<asp:Label ID="lblStage" runat="server" Text='<%#ShowStage(Eval("codingStage"))%>'></asp:Label>
</ItemTemplate>
in code behind:
protected string ShowStage(int codingStage)
{
switch (codingStage)
{
case 0:
return "All";
case 1:
return "Uncode";
case 2:
return "Code";
default:
return "All";
}
}
In the same RowDataBound event, check e.RowRowType to detect the Header row. Once you are in the Header row, find the dropdown with a FindControl call. Once you have the dropdown, save the selected value are text in an instance variable. Then you can access it when RowDataBound fires for data rows.

RadDatePicker in ASP.NET Gridview TemplateField

I've got a date picker field declared within a template field in a GridView as follows:
<asp:TemplateField HeaderText="Shipping Date">
<ItemTemplate>
<asp:Label ID="lblShippingDate" runat="server" CssClass="dnnFormLabel"
AssociatedControlID="ShippingDatePicker" />
<dnn:DnnDatePicker runat="server" ID="ShippingDatePicker" />
</ItemTemplate>
</asp:TemplateField>
I can select the date just fine and it appears in my label control - I then click on a standard asp:Button which finds the selected row and despite it finding all the other controls on the row including the label control displaying the selected date, the label's Text attribute is blank:
var txtShippingDate = row.Cells[7].FindControl("lblShippingDate") as Label;
Please note that I'm using the DotNetNuke dnn:DnnDatePicker control but this is actually a RadDatePicker under the covers.
Can anyone suggest how I can successfully read the value?
Thanks for looking :)
Try following after you find label:
if(txtShippingDate != null) {
string date = Request.Form[txtShippingDate.UniqueID].ToString();
}

getting the RadGrid checkbox column value in server

I have a RadGrid having a checkbox column, i have added the column as a ItemTemplate to make it editable in the regular mode.
<telerik:GridTemplateColumn UniqueName="IsSelected" DataField="IsSelected">
<ItemTemplate>
<asp:CheckBox ID="chkBoolean" runat="server" Checked='<%# Convert.ToBoolean(Eval("IsSelected")) %>'Enabled='<%# Convert.ToBoolean(Eval("IsSelectionDisable")) %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
Using this I am able to display a checkbox as editable. Now my problem is how do i get the checked value of the checkox for saving it when the user has changed the checkbox. On click of a button i need to get all the rows that are still checked and save them. The below code does not work as it does not get the checkbox. Is there any way possible to get the value.
foreach (GridDataItem item in rgUnavailResult.MasterTableView.Items)
{
(CheckBox)item["IsSelected"].Controls[0]
}
Thanks
Found the checkbox
((System.Web.UI.WebControls.CheckBox)(item["IsSelected"].FindControl("chkBoolean")))

ASP.NET Gridview Templatefield with multiple items

I am creating a web application in ASP.net/VB.NET and I have an issue with the GridView control.
Currently, I have the GridView populated with data from the DB and I've also coded the update button to allow the user to edit any necessary information through a form that pops up.
What I'd like to do, if possible, is add a button to the two right columns(I already put one in the Dock Out Time column) which will be invisible if the column is set or will set the current time to the column. Setting the time for those two columns is already handled through the update form, but my supervisor asked me to try and see if this was possible.
Those two Time columns are TemplateFields(since I format the display time from what is actually in the DB) and I added an asp button in the ItemTemplate for that Set Button in the picture.
Is this even possible to do and if so, how would I access this button in the code behind so I can add functionality(setting the time and hiding it if the column is not null)If it's not really possible to have two items like this in a TemplateField I can just make 2 extra columns for these buttons but I think this would look much cleaner.
Any input would be greatly appreciated. thank you for your time.
Yes this is possible, check this answer:
https://stackoverflow.com/a/11077709/1268570
Basically you need to handle the RowCommand event from the grid and identify each button with a command, optionally you can add arguments to each button when you bind, for example:
<asp:GridView runat="server" OnRowCommand="grdProducts_RowCommand"
ID="grdProducts">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false"
CommandName="myLink" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' Text="Button"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
In code behind:
protected void grdProducts_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "myLink":
this.lblMessage.Text = e.CommandName + " " + e.CommandArgument + " " + DateTime.Now.ToString();
// referenece to the current row
var row = this.grdProducts.Rows[int.Parse(e.CommandArgument.ToString())];
break;
default:
break;
}
}
After you update your grid in the RowCommand event, you should repopulate the grid data to render the changes

Resources