I am trying to utilize a details view and provide the edit feature for a few levels of user authorization. Basically level 1 users cannot update a predefined set of fields but level 2 users can update these fields. I had tried simply setting the field to visible=false when defining the EditTemplate and then in the DataBind I would test for authorization and make it visible=true if the user had privileges to update the field (see code example below). Worked like a charm, except I noticed that when level 1 users update the fields they are allowed to update, the visible=false fields would be set to null (overwritten) in the database. So, been trying various options not to have to duplicate the views etc.
code snippet:
aspx....
<asp:TemplateField HeaderText="<%$ Resources:Resource, Level %>"
SortExpression="LevelId">
<EditItemTemplate>
<asp:DropDownList ID="LevelList" runat="server"
DataTextField="LevelDesc" DataValueField="LevelId">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="<%$ Resources:Resource, Level1 %>"
SortExpression="Level1Date" Visible="false" >
<EditItemTemplate>
<asp:TextBox ID="Level1" runat="server" Text='<%#
Bind("Level1Date", "{0:d}") %>' />
<asp:CompareValidator ID="CompareValidator1" runat="server"
ErrorMessage="Please enter a valid date (m/d/y)"
ControlToValidate="Level1" Operator="DataTypeCheck"
Type="Date" Display="Dynamic">
</asp:CompareValidator>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="<%$ Resources:Resource, Level2 %>"
SortExpression="Level2Date" Visible="false" >
<EditItemTemplate>
<asp:TextBox ID="Level2" runat="server" Text='<%#
Bind("Level2Date", "{0:d}") %>' />
<asp:CompareValidator ID="CompareValidator2" runat="server"
ErrorMessage="Please enter a valid date (m/d/y)"
ControlToValidate="Level2" Operator="DataTypeCheck"
Type="Date" Display="Dynamic">
</asp:CompareValidator>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="<%$ Resources:Resource, Level4 %>"
SortExpression="Level4Date" Visible="false" >
<EditItemTemplate>
<asp:TextBox ID="Level4" runat="server" Text='<%#
Bind("Level4Date", "{0:d}") %>' />
</Fields>
aspx.cs SNIPPET
<name>_DataBound(object sender, EventArgs e)
{
.
.
.
if (User.IsInRole("yyy") || User.IsInRole("xxx))
{
OfficialProfileInfo.Fields[2].Visible = true;
OfficialProfileInfo.Fields[3].Visible = true;
}
You must set the DataKeyNames property for the automatic updating, deleting, and inserting features of the DetailsView control to work.
While updating if some fields should not change, you can put them in the key.
if (User.IsInRole("yyy") || User.IsInRole("xxx))
{
OfficialProfileInfo.Fields[2].Visible = true;
OfficialProfileInfo.Fields[3].Visible = true;
}
else
{
OfficialProfileInfo.DataKeyNames = "Level4Date"
}
Note: DataKeyNames is a comma-seperated list of field names/
Related
net gridview and I do not wish to use the built in controls and want to bind the data manually in c#. Could some one let me know where to start and how can I use 3 different drop downs to add more filtering?
asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvContactorRowDataBound" Gridlines="Vertical" >
<Columns >
<asp:TemplateField HeaderText="Full Name" SortExpression="contactname" HeaderStyle-BackColor="deepskyblue">
<EditItemTemplate>
<asp:TextBox ID="txtcontactname2" runat="server" Text='<%# Bind("contactname") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorcontactname2" runat="server" ErrorMessage="Full Name is required for contractor update!" Text="*" ForeColor="Red" ControlToValidate="txtcontactname2" display="none"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcontactname2" runat="server" Text='<%# Bind("contactname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="phone" HeaderText="Phone" SortExpression="phone" HeaderStyle-BackColor="deepskyblue"/>
<asp:BoundField DataField="email" HeaderText="Email" SortExpression="email" HeaderStyle-BackColor="deepskyblue"/>
You did not mentioned your scenario, therefore i assume that you want show all of students in grid view and in each row have a Drop down to select teacher. You have another data base Teachers and each teacher has Id and Name. So in your code behind you gathered all of the teachers:
protected List<teacher> teachers;
In each row of Students gridview you must have this column:
<asp:TemplateField HeaderText="Teacher">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="selectClip" DataSource="<%# teachers %>"
DataTextField="Name" DataValueField="Id" AppendDataBoundItems="true">
<asp:ListItem Text="<---Select Teacher--->"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblShowTeacher" runat="server" Text='<%# Bind("Teacher") %>' />
</ItemTemplate>
</asp:TemplateField>
If you want to have your teachers in a SqlDataSource, change this:
DataSource="<%# teachers %> to this: DataSourceId="teachersDataSourceId"
working on an ASP Gridview querying a SQL server base.
<asp:Content ID="i_cttContenu" runat="server" ContentPlaceHolderID="i_cphContenu">
<asp:SqlDataSource ID="i_sdsGvOption" runat="server" ConnectionString="<%$ ConnectionStrings:... %>"
SelectCommand=" SELECT * FROM MyTable " SelectCommandType="Text"
UpdateCommand="UPDATE MyTable SET [name] = #name, prenom = #prenom, isAlive = #isAlive WHERE idWsgProgramOption = #idWsgProgramOption" UpdateCommandType="Text"
</asp:SqlDataSource>
<asp:UpdatePanel ID="i_up" runat="server">
<ContentTemplate>
<asp:GridView ID="i_gvOption" runat="server" AutoGenerateColumns="False" DataKeyNames="idWsgProgramOption"
DataSourceID="i_sdsGvOption" EnableModelValidation="True">
<Columns>
<asp:CommandField ButtonType="Image" CancelImageUrl="~/....gif"
CancelText="Annuler" EditImageUrl="~/....gif"
EditText="Update" HeaderText="M" UpdateImageUrl="~/....gif"
UpdateText="Save">
</asp:CommandField>
<asp:TemplateField HeaderText="Nom" SortExpression="name">
<ItemTemplate>
<asp:HyperLink ID="i_hlOption" runat="server" NavigateUrl='<%# Eval("idWsgProgramOption", "~/myURL") %>'
Text='<%# Eval("name") %>' />
</ItemTemplate>
<EditItemTemplate>
<table >
<tr>
<td >
<asp:TextBox ID="i_tbNom" runat="server" Text='<%# Bind("name") %>' />
</td>
</tr>
</table>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="prenom" SortExpression="prenom">
<ItemTemplate>
<asp:HyperLink ID="i_hlprenom" runat="server" NavigateUrl='<%# Eval("prenom", "~/myURL") %>'
Text='<%# Eval("prenom") %>' />
</ItemTemplate>
<EditItemTemplate>
<table >
<tr>
<td >
<asp:TextBox ID="i_tbprenom" runat="server" Text='<%# Bind("prenom") %>' />
</td>
</tr>
</table>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Obligatoire" >
<ItemTemplate>
<asp:CheckBox ID="CB_id1" runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CB_id2" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
The update() method is not invoked when I click the update button (first column). If I add an onUpdating event into the datasource, the corresponding method is never invoked.
The code causing the issue is definitely the checkbox.
If I remove from the datasource update query:
, isAlive = #isAlive
and only set:
UPDATE MyTable SET [name] = #name, prenom = #prenom, isAlive = #isAlive WHERE idWsgProgramOption = #idWsgProgramOption;
Then it updates fine (except the isAlive field of course).
I am 100% sure that the isAlive field exists into the base (bit type).
So it looks that my problem comes from this bloc:
<asp:TemplateField HeaderText="Obligatoire" >
<ItemTemplate>
<asp:CheckBox ID="CB_id1" runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CB_id2" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
Is there anything obvious that I missed??
Also, this is the simplified code, but if I set the "checked" property to the checkbox and correctly binds, the rows checkbox is correctly field. So the issue does not affect the select but only the update.
Try a button column instead so you can specify the specific command names.
<asp:ButtonField ButtonType="Link" Text="Update" CommandName="Update" />
<asp:ButtonField ButtonType="Link" Text="Delete" CommandName="Delete" />
Take action based on e.CommandName.
I have a gridView as follows.
<asp:GridView ID="grvLocationCash" runat="server" AutoGenerateColumns="false" CssClass="gridtable" DataKeyNames="LocationId">
<Columns>
<asp:BoundField HeaderText="Location Name" DataField="LocationName" />
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="txtAmount" runat="server" CssClass="txtbox" Visible="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvAmount" runat="server" ControlToValidate="txtAmount" ErrorMessage="Please enter the Amount" Display="Dynamic" SetFocusOnError="true"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rgvAmount" runat="server" ControlToValidate="txtAmount" ValidationExpression="^\d+$" ErrorMessage="Please enter whole numbers only" Display="Dynamic" SetFocusOnError="true"></asp:RegularExpressionValidator>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and a save button with the following code.
<asp:Button ID="btnLocationAmountList" runat="server" OnClick="btnLocationAmountList_Click" Text="Save" Width ="100px" />
after the gridview is bound, there are about 20 rows in it.
When I type in numbers into the text box of the first row and press Enter key to go to second text box, the Required Field Validator is triggered for all the other 19 rows.
But, if I type numbers into the first text box and mouse click on the next text box, the RequiredFieldValidator is not triggered.
The page must be validated only if the Save button is clicked. Values must be entered for all the textboxes before save, and all the values must be integer only. (11,125,6589 etc).
How to enable disable validators for a particular control?
UPDATE: here is the page_load event code in my class file.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
FinanceServiceRef.FinanceServiceClient obj = new FinanceServiceRef.FinanceServiceClient("WSHttpBinding_IFinanceService");
var ds = obj.ViewLocationAmountCashManagement();
grvLocationCash.DataSource = ds;
grvLocationCash.DataBind();
}
You need to handle the onkeydown in each text box in each ItemTemplate, like this:
onkeydown = "return (event.keyCode!=13);"
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="txtAmount" runat="server" CssClass="txtbox"
Visible="true"
onkeydown = "return (event.keyCode != 13);">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
Note: The Enter key has a keyCode value of 13.
Did you try using Validation Group property?
<asp:GridView ID="grvLocationCash" runat="server" AutoGenerateColumns="false" CssClass="gridtable" DataKeyNames="LocationId">
<Columns>
<asp:BoundField HeaderText="Location Name" DataField="LocationName" />
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="txtAmount" runat="server" CssClass="txtbox" Visible="true"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvAmount" runat="server" ControlToValidate="txtAmount" ErrorMessage="Please enter the Amount" Display="Dynamic" SetFocusOnError="true" ValidationGroup="save"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rgvAmount" runat="server" ControlToValidate="txtAmount" ValidationExpression="^\d+$" ErrorMessage="Please enter whole numbers only" Display="Dynamic" SetFocusOnError="true" ValidationGroup="save"></asp:RegularExpressionValidator>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnLocationAmountList" runat="server" OnClick="btnLocationAmountList_Click" Text="Save" Width ="100px" ValidationGroup="save" />
I have a list of games. Each game has a visiting team and a home team. I would like to allow the user to choose either the visiting team or the home team. So I converted to template fields and put radio buttons in. But clearly that isn't right. I need a radio button list, I think. Because with just radio buttons, they can select both. is this possible with a gridview? most tutorials I see only have one radio button in the row, so this isn't the issue. here is my gridview:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="id_game" DataSourceID="sqlPopulateGames">
<Columns>
<asp:BoundField DataField="id_game" HeaderText="id_game" InsertVisible="False" ReadOnly="True" SortExpression="id_game" />
<asp:TemplateField HeaderText="visitor" SortExpression="visitor">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("visitor") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<br />
<asp:RadioButton ID="RadioButton1" runat="server" Text='<%# Eval("visitor") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="home" SortExpression="home">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("home") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:RadioButton ID="RadioButton2" runat="server" Text='<%# Eval("home") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="game_time" HeaderText="game_time" SortExpression="game_time" />
</Columns>
</asp:GridView>
because with just radio buttons, they can select both.
Not if those radio buttons are grouped in the markup. Radio buttons are designed to be mutually-exclusive, but they need to know which other radio buttons to be exclusive with. The GroupName property in ASP.NET is used to set this.
Something like this:
<asp:RadioButton GroupName="SomeGroup" ID="RadioButton1" runat="server" Text='<%# Eval("visitor") %>' />
With that set, this would be mutually exclusive for any other RadioButton with the GroupName set to "SomeGroup".
Since this is happening inside a repeated control, you probably want a separate group for each iteration. So you can bind it to some value in the backing data:
<asp:RadioButton GroupName='<%# Eval("someValue") %>' ID="RadioButton1" runat="server" Text='<%# Eval("visitor") %>' />
If someValue is unique for each record in the result, then you would end up with a grouped pair of mutually exclusive radio buttons for each row.
I have a dropdownlist inside a detailsview where I will be editing records inside the details view. My problem is dropdownlist inside the details view is bind to a field and giving an error
'DropDownList1' has a SelectedValue which is invalid because it does
not exist in the list of items. Parameter name: value
This is due to the selectedvalue value is not in the dropdownlist.
Can someone tell me how to handle this error. I want to use try catch and do nothing and just ignore the error or maybe pass a blank value as selectedvalue in the dropdown.
Main problem I have is I am not sure where to put the try catch statement.
Complete code is below.
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
DataKeyNames="RecordRef" DataSourceID="EntityDataSource1" Height="50px"
Width="125px">
<Fields>
<asp:BoundField DataField="RecordRef" HeaderText="RecordRef" ReadOnly="True"
SortExpression="RecordRef" />
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID"
SortExpression="CustomerID" />
<asp:TemplateField HeaderText="JobCategory" SortExpression="JobCategory">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="EntityDataSource2" DataTextField="ItemValue"
DataValueField="ItemValue" SelectedValue='<%# Bind("JobCategory") %>'>
</asp:DropDownList>
<asp:EntityDataSource ID="EntityDataSource2" runat="server"
ConnectionString="name=CRMSEntities" DefaultContainerName="CRMSEntities2"
EnableFlattening="False" EntitySetName="KeyValues">
</asp:EntityDataSource>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("JobCategory") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("JobCategory") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="JobDescription" HeaderText="JobDescription"
SortExpression="JobDescription" />
<asp:BoundField DataField="JobDate" HeaderText="JobDate"
SortExpression="JobDate" />
<asp:BoundField DataField="JobStatus" HeaderText="JobStatus"
SortExpression="JobStatus" />
<asp:BoundField DataField="Referral" HeaderText="Referral"
SortExpression="Referral" />
<asp:CommandField ShowEditButton="True" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
You can handle exception with override OnRender method of your usercontrol with using try catch around base.Render
Rather than using Try ... Catch, you could use the following in code behind (VB in this case):
Dim ddlItem As ListItem
ddlItem = myDDL.Items.FindByValue(UserInput.ToString())
If Not ddlItem Is Nothing Then
ddlItem.Selected = True
Else
myDDL.Text = "Some text to indicate failure"
End If