I am using Visual Studio 2013. I have a ASP.net (vb) Webforms site with asp.net identity. I trying to create a page that manages User role and create roles. I cant find any help online for this when it comes to web forms. This code works for asp.net membership but not for Identity. Here is my code.
Please help Thanks.
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports Microsoft.Owin.Security
Imports Owin
Partial Class AssignRoles
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Roles.AddUserToRole(DropDownList5.SelectedValue, DropDownList6.SelectedValue)
Label1.Text = DropDownList5.SelectedValue + " Was added to the " + DropDownList6.SelectedValue + " Role."
End Sub
Protected Sub btnremoverole_Click(sender As Object, e As EventArgs) Handles btnremoverole.Click
Roles.RemoveUserFromRole(DropDownList3.SelectedValue, DropDownList4.SelectedValue)
Label1.Text = DropDownList3.SelectedValue + " Was removed from the " + DropDownList4.SelectedValue + " Role."
End Sub
Protected Sub CreateRole_Click(sender As Object, e As EventArgs) Handles CreateRole.Click
Dim createRole As String = RoleTextBox.Text
Try
If Roles.RoleExists(createRole) Then
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' already exists. Please specify a different role name."
Return
End If
Roles.CreateRole(createRole)
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' created."
' Re-bind roles to GridView.
Catch
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' <u>not</u> created."
End Try
End Sub
End Class
Here is the Markup code
<%# Page Title="Admin Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="true"CodeBehind="AssignRoles.aspx.vb" Inherits="Conflict_Minerals.AssignRoles" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="row">
<div class="col-md-12">
<h2>Admin Panel</h2>
<br />
</div>
<div class="col-md-8">
<asp:Label ID="Label3" runat="server" Text="Add user to role: "></asp:Label>
<asp:DropDownList ID="DropDownList5" runat="server" DataSourceID="SqlDataSource1" DataTextField="UserName" DataValueField="UserName">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList6" runat="server" DataSourceID="SqlDataSource2" DataTextField="Name" DataValueField="Name">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Add user to role" />
</div>
<div class="col-md-8">
<br />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Remove user from role: "></asp:Label>
<asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="SqlDataSource1" DataTextField="UserName" DataValueField="UserName">
</asp:DropDownList>
 <asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="SqlDataSource2" DataTextField="RoleName" DataValueField="RoleName">
</asp:DropDownList>  
<asp:Button ID="btnremoverole" runat="server" Text="Remove user from role" Height="26px" />
<br />
<br />
<div>
<h2>Manage Roles</h2>
</div>
<br />
<asp:TextBox ID="RoleTextBox" runat="server"></asp:TextBox>
<asp:Button ID="CreateRole" runat="server" Text="Create Role" />
<br />
<br />
<asp:Label ID="Msg" runat="server" Text="Label"></asp:Label>
<br />
<br />
<br />
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT [Name] FROM [vw_AspNetRoles]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT [UserName] FROM [AspNetUsers]"></asp:SqlDataSource>
<br />
<br />
</div>
</div>
</asp:Content>
I found a solution here is my code
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports Microsoft.Owin.Security
Imports Owin
Partial Class AssignRoles
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim UserManager = New UserManager(Of IdentityUser)(New UserStore(Of IdentityUser)(New IdentityDbContext()))
UserManager.AddToRole(DropDownList5.SelectedValue, DropDownList6.SelectedValue)
Label1.Text = DropDownList5.SelectedItem.Text + " Was added to the " + DropDownList6.SelectedValue + " Role."
End Sub
Protected Sub btnremoverole_Click(sender As Object, e As EventArgs) Handles btnremoverole.Click
Dim UserManager = New UserManager(Of IdentityUser)(New UserStore(Of IdentityUser)(New IdentityDbContext()))
UserManager.RemoveFromRoles(DropDownList3.SelectedValue, DropDownList4.SelectedValue)
Label1.Text = DropDownList3.SelectedItem.Text + " Was removed from the " + DropDownList4.SelectedValue + " Role."
End Sub
Protected Sub CreateRole_Click(sender As Object, e As EventArgs) Handles CreateRole.Click
Dim createRole As String = RoleTextBox.Text
Dim RoleManager = New RoleManager(Of IdentityRole)(New RoleStore(Of IdentityRole)(New ApplicationDbContext()))
Try
If RoleManager.RoleExists(createRole) Then
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' already exists. Please specify a different role name."
Return
End If
RoleManager.Create(New IdentityRole(createRole))
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' created."
' Re-bind roles to GridView.
Catch
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' <u>not</u> created."
End Try
End Sub
End Class
You're going to need to instantiate a RoleManager to work with the roles. From there you can replace your AddRole and RemoveRole code. You will need a UserManager to assign roles to users. Here is a walkthrough for WebForms.http://www.asp.net/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/membership-and-administration
Related
I'm making E-Commerce website. Under that I want to show particular product details. From query string I can do that but that is not seo friendly so I need to make product name in url(from db) instead of using querystring. I tried following code but it is not working for me.
Error - The resource could not be Found
Global.asax
<%# Application Language="VB" %>
<%# Import Namespace="System.Web.Optimization" %>
<%# Import Namespace="System.Web.Routing" %>
<script runat="server">
Sub Application_Start(sender As Object, e As EventArgs)
RouteConfig.RegisterRoutes(RouteTable.Routes)
BundleConfig.RegisterBundles(BundleTable.Bundles)
End Sub
Private Shared Sub RegisterRoutes(routes As RouteCollection)
routes.MapPageRoute("product-detail", "{product_name}.aspx", "product-detail.aspx")
End Sub
</script>
product-detail.aspx (Dynamic Page)
Private Sub product_detail_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim pageName As String = Me.Page.RouteData.Values("product_name").ToString()
End If
End Sub
shop.aspx (used listview control to display list of products)
<asp:ListView ID="products" runat="server" DataKeyNames="ID">
<ItemTemplate>
<asp:HyperLink ID="productID" runat="server" NavigateUrl='<%# Eval("product_name", "~/{0}") %>' CssClass="product-link">
<!--blocks-starts--><div class="blocks blocks-shop">
<asp:Image ID="readyStock" runat="server" ImageUrl="images/common/ready_stock_tag.png" Visible="false" CssClass="tag" />
<asp:Label ID="checkReadyStock" runat="server" Visible="false"></asp:Label>
<div class="block-img">
<img src='<%# Eval("image") %>' runat="server" id="proImg" />
</div>
<div class="block-content">
<span class="sku" style="font-size:0.6em !important">Item No. <asp:Label ID="skuID" runat="server" Text='<%# Eval("sku") %>'></asp:Label></span>
<h3>
<asp:Label ID="prodName" runat="server" Text='<%# Eval("product_name") %>'></asp:Label></h3>
<p><strong>
<asp:Label ID="priceRange" runat="server" Text='<%# Eval("price_range") %>'></asp:Label></strong></p>
</div>
</div><!--blocks-ends-->
</asp:HyperLink>
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholderContainer" runat="server" style="">
<div runat="server" id="itemPlaceholder" />
</div>
</LayoutTemplate>
</asp:ListView>
shop.aspx.vb
Private Sub shop_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Try
Dim str As String = "select * from products where status = 'active'"
Dim cmd As New MySqlCommand(str, con)
con.Open()
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
products.DataSource = dt
products.DataBind()
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End Sub
I want to display list of clinics details in listview. From MasterPage Users selects the city & If he goes to clinincs page then list of hospitals display from selected city. Now If I use ViewState in my clinics page then It does not gets clinics data from selected city So what I have done I store City session & on clinics page I have used Session instead of ViewState Which is now working right but my datagaer stopped working. If I have to see another page from datapager then it doesn't switch over. Here is my code
MasterPage
Protected Sub locationSelector_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles locationSelector.TextChanged
Session("masterLocation") = locationSelector.text
Session("Data") = Nothing
End Sub
Clinics Page
Private Sub hospitals_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
Try
If Not Session("Data") Is Nothing Then
hospitals.DataSource = Session("Data")
hospitals.DataBind()
Else
Dim citySelector As Label = Page.Master.FindControl("locationPopupActivator")
query = "select hospitalid, name, address, thumbnail, serviceID, mondayFrom, mondayTo, consultancyFees, city from hospitals Where city Like '" + citySelector.Text + "%' and status = 'active'"
Dim cmd As New MySqlCommand(query, con)
cmd.CommandTimeout = 120
Dim da As New MySqlDataAdapter(cmd)
Dim table As New DataTable
da.Fill(table)
Session("Data") = table
hospitals.DataSource = table
hospitals.DataBind()
End If
'mainCount.Text = table.Rows(0)("countRows").ToString
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Protected Sub DataPager1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Try
Dim table As DataTable = Session("Data")
hospitals.DataSource = table
hospitals.DataBind()
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Listview on ASPX
<asp:ListView ID="hospitals" runat="server" DataKeyNames="hospitalID" DataKey="hospitalID">
<ItemTemplate>
My Content
</ItemTemplate>
<EmptyDataTemplate>
<div class="not-found">
<p>
Sorry! Selected Query Not Found</p>
<center>
<img src="images/not-found.jpg" /></center>
</div>
</EmptyDataTemplate>
<LayoutTemplate>
<ul id="itemPlaceholderContainer" runat="server" style="">
<li runat="server" id="itemPlaceholder" />
</ul>
<div class="datapager" style="padding-bottom: 10px;">
<asp:DataPager ID="DataPager1" runat="server" PageSize="10" PagedControlID="hospitals" ViewStateMode="Enabled">
<Fields>
<asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="true" ShowNextPageButton="false" />
<asp:NumericPagerField ButtonType="Link" />
<asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false" ShowPreviousPageButton="false" />
</Fields>
</asp:DataPager>
</div>
</LayoutTemplate>
</asp:ListView>
This is working sample of your page:
hospital.master
<%# Master Language="VB" CodeFile="hospital.master.vb" Inherits="hospital_master" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" runat="server" />
<div>
<asp:Label ID="lblLockSel" runat="server" AssociatedControlID="locationSelector">Locator Selector</asp:Label>
<asp:UpdatePanel ID="upLocSel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="locationSelector" runat="server" AutoPostBack="true"></asp:TextBox>
<asp:Label ID="locationPopupActivator" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
hospital.master.vb
Partial Class hospital_master
Inherits System.Web.UI.MasterPage
Protected Sub locationSelector_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles locationSelector.TextChanged
Session("masterLocation") = locationSelector.Text
Session("Data") = Nothing
locationPopupActivator.Text = locationSelector.Text
End Sub
End Class
clinics.aspx
<%# Page Title="" Language="VB" MasterPageFile="~/hospital.master" AutoEventWireup="false" CodeFile="clinics.aspx.vb" Inherits="Clinics" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:UpdatePanel ID="upHospitals" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:ListView ID="hospitals" runat="server" DataKeyNames="hospitalID" DataKey="hospitalID">
<ItemTemplate>
<%--My Content--%>
<li>
<asp:HyperLink ID="lnkHospital" runat="server" NavigateUrl='<%#Eval("hospitalID", "~/hospital.aspx?id={0}") %>' Text='<%#Eval("Name") %>'></asp:HyperLink>
</li>
</ItemTemplate>
<EmptyDataTemplate>
<div class="not-found">
<p>
Sorry! Selected Query Not Found</p>
<center><%--<center>Is Deprecated Use div with CSS</center>--%>
<img src="images/not-found.jpg" /></center>
</div>
</EmptyDataTemplate>
<LayoutTemplate>
<ul>
<li runat="server" id="itemPlaceholder" />
</ul>
</LayoutTemplate>
</asp:ListView>
<%--Inside Update Panel dataPager should be outside paged control--%>
<div class="datapager" style="padding-bottom: 10px;">
<asp:DataPager ID="DataPager1" runat="server" PageSize="10" PagedControlID="hospitals"><%-- ViewStateMode="Enabled"> this is default--%>
<Fields>
<asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="true" ShowNextPageButton="false" />
<asp:NumericPagerField ButtonType="Link" />
<asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false" ShowPreviousPageButton="false" />
</Fields>
</asp:DataPager>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
clinics.aspx.vb
Partial Class Clinics
Inherits System.Web.UI.Page
Private Sub Clinics_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Session.Remove("Data") 'init
End If
End Sub
Private Sub hospitals_PagePropertiesChanging(sender As Object, e As PagePropertiesChangingEventArgs) Handles hospitals.PagePropertiesChanging
DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, False)
hospitals.DataSource = GetData() 'Session("Data")
hospitals.DataBind()
End Sub
Private Sub hospitals_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
hospitals.DataSource = GetData()
hospitals.DataBind()
End Sub
Private Function GetData() As Data.DataTable
Try
If Session("Data") IsNot Nothing Then
Return Session("Data")
Else
'This is MS SQL server. If you use MySQL then change types accordingly
DataPager1.SetPageProperties(0, DataPager1.PageSize, False) 'reinit
Dim citySelector As Label = Page.Master.FindControl("locationPopupActivator")
Using con As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ClinicsCNN").ConnectionString)
Dim cmd As New Data.SqlClient.SqlCommand("select hospitalid, name, address, thumbnail, serviceID, mondayFrom, mondayTo, consultancyFees, city from hospitals Where city Like #city and status = 'active'", con)
cmd.CommandType = Data.CommandType.Text
cmd.Parameters.Add("#city", Data.SqlDbType.VarChar, 50).Value = citySelector.Text & "%" 'same as Session("masterLocation")
Dim table As New Data.DataTable()
Dim da As New Data.SqlClient.SqlDataAdapter(cmd)
da.Fill(table)
da.Dispose()
cmd.Dispose()
Session("Data") = table
Return table
End Using
End If
Catch ex As Exception
Response.Write(ex) 'for debug purpose
Return Nothing
End Try
End Function
End Class
Do you accept this solution?
Ok, after your comments here is my code that works for me:
Private Sub hospitals_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
Try
If Session("Data") Is Nothing Then
Dim citySelector As Label = Page.Master.FindControl("locationPopupActivator")
query = "select hospitalid, name, address, thumbnail, serviceID, mondayFrom, mondayTo, consultancyFees, city from hospitals Where city Like '" + citySelector.Text + "%' and status = 'active'"
Dim cmd As New MySqlCommand(query, con)
cmd.CommandTimeout = 120
Dim da As New MySqlDataAdapter(cmd)
Dim table As New DataTable
da.Fill(table)
Session("Data") = table
hospitals.DataSource = table
hospitals.DataBind()
End If
'mainCount.Text = table.Rows(0)("countRows").ToString
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
protected void hospitals_PagePropertiesChanging(object sender, System.Web.UI.WebControls.PagePropertiesChangingEventArgs e)
{
var datapager = ((DataPager)hospitals.FindControl("DataPager1"));
datapager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
hospitals.DataSource = Session["Data"];
hospitals.DataBind();
datapager.DataBind();
}
I don't think you need DataPager1_PreRender method at all so probably you should remove it all together. You will need to attach new event to your list view: OnPagePropertiesChanging="hospitals_PagePropertiesChanging". Sorry for code in c#, but I don't know VB very well ;)
I have a webpage that won't let me sort a dropdownlist. I have a SQLDataSource connection configured to bring up the rows Description in the table tblCodesWorkNotRec. When I go to Order By and choose sort by Description, and then test the query, I'm getting an error -
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
Why?
If you need to see code, what code - aspx or vb?
Here is the vb code:
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Mvc
Partial Class TimeOffAddNoRequest
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Once data is edited on this webpage, do not go back to first loaded data (data from gridview)
If Page.IsPostBack = True Then
Return
End If
Dim windowsLoginName As System.String = HttpContext.Current.User.Identity.Name 'System.Security.Principal.WindowsIdentity.GetCurrent().Name
Dim split As String() = Nothing
Dim vname As String
Dim sqlConnection As New SqlConnection("Data Source=janetdev;Initial Catalog=TimeSQL;Persist Security Info=True;User ID=sa;Password=password")
Dim cmd, cmd1, cmd2 As New SqlCommand
Dim returnValue, returnValue1, returnValue2 As Object
Dim dt As Date
dt = Today
MsgBox(Today)
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get firstname from tblEmployees that matches login name
cmd.CommandText = "SELECT FirstName FROM tblEmployees where login = '" & vname & "'"
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection
'Get lastname from tblEmployees that matches login name
cmd1.CommandText = "SELECT LastName FROM tblEmployees where login = '" & vname & "'"
cmd1.CommandType = CommandType.Text
cmd1.Connection = sqlConnection
'Get employeeid from tblEmployees that matches login name
cmd2.CommandText = "SELECT EmployeeID FROM tblEmployees where login = '" & vname & "'"
cmd2.CommandType = CommandType.Text
cmd2.Connection = sqlConnection
sqlConnection.Open()
'firstname
returnValue = cmd.ExecuteScalar()
'lastname
returnValue1 = cmd1.ExecuteScalar()
'employeeid
returnValue2 = cmd2.ExecuteScalar()
sqlConnection.Close()
'display firstname and lastname on screen
TextBox3.Text = returnValue & " " & returnValue1
TextBox4.Text = returnValue2
'display today's date
DateRequested.Text = dt
'Get value of other fields
If Not [String].IsNullOrEmpty(Request.QueryString("BeginDateOff").ToString()) Then
'Retrieving the BeginDateOff Value
BeginDate.Text = Request.QueryString("BeginDateOff").ToString()
End If
If Not [String].IsNullOrEmpty(Request.QueryString("EndDateOff").ToString()) Then
'Retrieving the EndDateOff Value
EndDate.Text = Request.QueryString("EndDateOff").ToString()
End If
If Not [String].IsNullOrEmpty(Request.QueryString("BeginTimeOff").ToString()) Then
'Retrieving the BeginTimeOff Value
BeginTimeDD.SelectedValue = Request.QueryString("BeginTimeOff").ToString
End If
If Not [String].IsNullOrEmpty(Request.QueryString("EndTimeOff").ToString()) Then
'Retrieving the EndTimeOff Value
EndTimeDD.Text = Request.QueryString("EndTimeOff").ToString()
End If
'Retrieving the All Day Value
AllDay.Checked = Boolean.Parse(Request.QueryString("AllDay_YesNo"))
'AllDay.Checked = Request.QueryString("AllDay_YesNo")
'Retrieving the WorkHoursNotRecordID
wkid.Text = Request.QueryString("WorkHoursNotRecordID").ToString()
If Request.QueryString("description").ToString = "Unknown" Then
Label2.Text = "You must change the reason from Unknown."
DropDownList2.Focus()
Exit Sub
Else
'Retrieving the Description Value
DropDownList2.Text = Request.QueryString("Description").ToString()
End If
BeginDate.Focus()
End Sub
And here is the aspx code:
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="TimeOffAddNoRequest.aspx.vb" Inherits="timework.TimeOffAddNoRequest" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:ToolkitScriptManager ID="toolkitScriptManager" runat="server" />
<asp:Label ID="Label2" runat="server"
style="color: #990033; font-weight: 700"></asp:Label>
<asp:Label ID="Label1" runat="server"
style="color: #000099; font-weight: 700"></asp:Label>
<br />
<label>Employee Name:</label><asp:TextBox ID="TextBox3" runat="server" BorderStyle="None"
style="margin-left: 7px; font-size: medium; font-weight: 700;"
Width="150px" Height="22px" AutoPostBack="True"></asp:TextBox>
<asp:TextBox ID="TextBox4" runat="server" Width="129px"
AutoPostBack="True" Visible="False"></asp:TextBox>
<br />
<hr align="left" style="width: 791px; margin-left: 0px" />
<label>Date Requested:<asp:TextBox ID="DateRequested" runat="server" style="margin-left: 9px; font-size: medium; font-weight: 500;"
Width="150px" Height="22px" AutoPostBack="True" BorderStyle="None"></asp:TextBox>
</label>
<br />
<br />
<label>Begin Date Off:</label>
<asp:TextBox ID="BeginDate" runat="server" style="margin-left: 10px; font-size: medium; font-weight: 500;"
Width="150px" Height="22px" AutoPostBack="True" BorderStyle="Solid"
BorderWidth="1px"></asp:TextBox>
<label> End Date Off:</label>
<asp:TextBox ID="EndDate" runat="server" style="margin-left: 15px; font-size: medium; font-weight: 500;"
Width="150px" Height="22px" AutoPostBack="True" BorderStyle="Solid"
BorderWidth="1px"></asp:TextBox>
<br />
<br />
<label> All Day?</label>
<asp:CheckBox ID="AllDay" runat="server" AutoPostBack="True" />
<label> Begin Time Off:</label> <label>
<asp:DropDownList ID="BeginTimeDD" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Time" DataValueField="Time"
Height="26px" Width="100px">
</asp:DropDownList>
End Time Off:</label> <asp:DropDownList ID="EndTimeDD"
runat="server" DataSourceID="SqlDataSource1" DataTextField="Time"
DataValueField="Time" Height="26px" Width="100px">
</asp:DropDownList>
<br />
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TimeSQLConnectionString2 %>"
SelectCommand="SELECT [Time] FROM [tblCodesTime] ORDER BY [Time]">
</asp:SqlDataSource>
<label> Reason:</label>
<asp:DropDownList
ID="DropDownList2" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource2" DataTextField="Description"
DataValueField="Description" Height="26px" Width="149px">
</asp:DropDownList>
<br />
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:TimeSQLConnectionString1 %>"
SelectCommand="SELECT [Description] FROM [tblCodesWorkNotRec] ORDER BY [Description]">
</asp:SqlDataSource>
<asp:TextBox ID="wkid" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button2" runat="server" Text="Save" />
<br />
<br />
</asp:Content>
I believe your error is in your aspx on this line
SELECT [Description] FROM [tblCodesWorkNotRec] ORDER BY [Description]
The order by description is going to be what is giving you that error. You can fix this by casting to a varchar:
SELECT [Description]
FROM [tblCodesWorkNotRec]
ORDER BY Convert(varchar(max), [Description])
I'm not sure why you would want to order by a description field however. Perhaps its best just to do away with the order by. The error may also have occured on the order by [time] line. But if this is a DateTime field its fine. This field should probably be renamed to something that is not a keyword, like CodeTime
Some other notes on your code, Refactoring this is a good idea.
As a recommendation, I would make a single class that talks to your database. Dont put sql connections in your code behind, much less in your aspx. (if you are going to do that, pick one location, not both) This class will have all your sql and returns just the values you want.
Consolidate your sql. There is no reason to make 3 calls to the same table to get one value from each call. Make one call to get 3 things. I'm speaking of the firstname, lastname, employeeid calls.
Dont put business logic in event handlers. Notice your Page_Load method. This is an event handler. Any code that you put here cannot be called from somewhere else, so you end up copying code over and over. Simply move the calls to their own method, and call that method from Page_Load. (GoF pattern - Facade)
Put your UI elements in their own div tag and align them with CSS. Get rid of (or at least think hard about) the <br/> and markup and use things like margin in css to move your elements around. Also move all the inline style tags to css.
I am learning ASP.NET 4 and i am trying to a form which the user enter details into text boxes and drop downs and then presses enter to complete form and the details go into a database in Oracle. What i would like to do is when the enter button is pressed i would like it to clear the form of anything entered and then show a message to say something like 'Thank you for your details'.
The form is working and records all the information to the database so all i need help with is clearing the form after button pressed and then to show message.
I'm not sure what code i need to show you so please ask if you do or anything else if i have not explained myself enough.
Thanks
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="StyleSheet.css" rel="stylesheet" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="navigationB">
<ul id="nav">
<li>Home</li>
<li>News</li>
<li>Contact</li>
<li>About</li>
<li>Finance Help</li>
</ul>
</div>
<div id="dform">
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
<h3 id="head3"><u>Please Enter Your Details:</u></h3>
Enter Your Name:
<asp:TextBox ID="nameB" runat="server"></asp:TextBox>* <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="You Must Provide Your Name" ControlToValidate="nameB"></asp:RequiredFieldValidator>
<br />
Enter Your Age:
<asp:TextBox ID="ageB" runat="server"></asp:TextBox>* <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="ageB" ErrorMessage="You Must Enter Your Age"></asp:RequiredFieldValidator> <asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Age Must be Between 1-99" ControlToValidate="ageB" MaximumValue="99" MinimumValue="1" SetFocusOnError="True"></asp:RangeValidator>
<br />
<br />
Male:
<asp:CheckBox ID="cbMale" runat="server" groupname="sexB" />
<br />
Female:
<asp:CheckBox ID="cbFemale" runat="server" groupname="sexB"/>
<br />
<br />
<h3 id="header3"><u>Select Hospital Department</u></h3>
<asp:DropDownList ID="DDList" runat="server" Width="201px">
</asp:DropDownList>*
<asp:DropDownList ID="DDList2" runat="server" Width="145px">
</asp:DropDownList>*
<br />
<asp:RequiredFieldValidator runat="server" ErrorMessage="You Must Select One Option" ControlToValidate="DDList"></asp:RequiredFieldValidator>
  ; <asp:RequiredFieldValidator ID="RequiredFieldValidator" runat="server" ErrorMessage="You Must Select One Option" ControlToValidate="DDList2"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="ButtonEnt" runat="server" Text="Enter"/> <asp:Button id="btnReset" onclick="btnReset_Click" runat="server" Text="Reset Form"></asp:Button>
<br />
<br />
<asp:Label ID="requiredField" runat="server" Text="(*) Denotes Required Field"></asp:Label>
<br />
</div>
</form>
</body>
</html>
My Function..
Imports Microsoft.VisualBasic
Imports Oracle.DataAccess.Client
Imports System.Data
Public Class sqlFunc
Public Shared Function tableData() As DataSet
Dim oraConnect As New OracleConnection
oraConnect.ConnectionString = ConfigurationManager.ConnectionStrings("smart_dev").ConnectionString
Dim oraCommand As New OracleCommand
oraCommand.Connection = oraConnect
oraCommand.CommandType = Data.CommandType.Text
Dim lsSQL As String = ""
lsSQL = "SELECT code, description FROM ref_code WHERE domain = 'SPECIALTY'"
oraCommand.CommandText = lsSQL
Dim da As New OracleDataAdapter(oraCommand)
Dim ds As New DataSet
da.Fill(ds)
Return ds
End Function
Public Shared Function tableData2() As DataSet
Dim oraConnect As New OracleConnection
oraConnect.ConnectionString = ConfigurationManager.ConnectionStrings("smart_dev").ConnectionString
Dim oraCommand As New OracleCommand
oraCommand.Connection = oraConnect
oraCommand.CommandType = Data.CommandType.Text
Dim lsSQL As String = ""
lsSQL = "SELECT code, description FROM ref_code WHERE domain = 'CATEGORY'"
oraCommand.CommandText = lsSQL
Dim da As New OracleDataAdapter(oraCommand)
Dim ds As New DataSet
da.Fill(ds)
Return ds
End Function
Public Shared Function dataInsertTable(ByVal sName As String, ByVal iAge As Integer, ByVal sSelect As String, ByVal dList As String, ByVal dList2 As String) As String
Dim answer As String = "Y"
Dim conSmart As New OracleConnection
conSmart.ConnectionString = ConfigurationManager.ConnectionStrings("smart_dev").ConnectionString
Dim oraCommand As New OracleCommand
oraCommand.CommandType = Data.CommandType.Text
oraCommand.Connection = conSmart
Dim lsSQL2 As String = ""
lsSQL2 = "INSERT INTO TEST_JC VALUES ('" & sName & "','" & iAge & "','" & sSelect & "','" & dList & "','" & dList2 & "' , sysdate )"
oraCommand.CommandText = lsSQL2
Try
conSmart.Open()
oraCommand.ExecuteNonQuery()
conSmart.Close()
Catch ex As Exception
answer = ex.Message
End Try
Return answer
End Function
End Class
put these lines like this in your button click event after saving values in database :
nameB.Text = "";
ageB.Text = "";
...
cbMale.Checked = false;
...
and bind your dropdownlists again too and finally show your message
On submit do,
call Clear();
public void Clear()
{
txtname.text="";
txtage.text="";
}
Protected void btnsubmit_click()
{
Scriptmanager.Registerstartupscript(this, GetType(), "show your alert message","showalert()", true)
Clear();
}
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
ScriptManager.RegisterStartupScript(Me, [GetType](), "displayalertmessage", "Showalert();", True)
txtname.Text = ""
txtage.Text = ""
dropdownlist.Text = ""
End Sub
This will Help you.
I have this event written in asp.net(VS2012). I want the user to upload an image and description, after upload I want to display the image name and description in grid view on the page and allow to upload next image. I am not sure why the event gets called twice and the second time I get "Object reference not set to...." error at "if strfile.hasfile...". Hope I explained it correctly.
Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
Dim strfilename, strfilepath As String
strfilename = Nothing
strfilepath = lblInciID.Text.Trim
Try
' Dim CurrentPath As String = Server.MapPath("C:\DSimages\")
If strFile.HasFile Then
Try
strFile.SaveAs("C:\DSimages\" & _
strfilepath + strFile.FileName)
'Save the name in the table
strfilename = strFile.PostedFile.FileName
strfilename = strfilepath + strfilename
If strFile.HasFile Then strFile = Nothing
Catch ex As Exception
MsgBox("ERROR: " & ex.Message.ToString())
End Try
End If
ImageDS.InsertParameters("ImagePath").DefaultValue = strfilename.Trim
ImageDS.InsertParameters("ImageDescription").DefaultValue = txtPicDesc.Text.Trim()
ImageDS.InsertParameters("InciID").DefaultValue = lblInciID.Text.Trim()
ImageDS.InsertParameters("Category").DefaultValue = lblCategory.Text.Trim()
ImageDS.Insert()
'MsgBox("Picure was uploaded successfully! Upload another picture or click on 'Cancel'")
txtPicDesc.Text = ""
Catch ex As Exception
MsgBox(ex.Message)
End Try
GridView_Image.Visible = True
End Sub
aspx page:
<div class="clearclass padtop">
<div class="div2">
<h4 style="width:23.2em">Browse file</h4>
<asp:FileUpload runat="server" ID="strFile" width="25em" Height="30px"/><br />
<asp:Label runat="server" ID="imgtoupload"></asp:Label>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorFile" runat="server" ErrorMessage="File" ControlToValidate="strFile"
CssClass="fontred style_bold" Display="Static">File</asp:RequiredFieldValidator>
</div>
<div class="div2">
<h4 style="width:24.6em">Add Description</h4>
<asp:TextBox runat="server" ID="txtPicDesc" Width="30.4em" Height="5em" TextMode="MultiLine"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorDesc" runat="server" ControlToValidate="txtPicDesc" CssClass="fontred style_bold"
ErrorMessage="Description">Description</asp:RequiredFieldValidator>
</div>
</div>
<asp:GridView ID="GridView_Image" runat="server" DataSourceID="ImageDS" AutoGenerateColumns="False" HorizontalAlign="Center" Visible="false">
<Columns>
<asp:BoundField DataField="InciID" HeaderText="InciID" SortExpression="InciID" />
<asp:BoundField DataField="Imagepath" HeaderText="Imagepath" SortExpression="Imagepath" />
<asp:BoundField DataField="ImageDescription" HeaderText="ImageDescription" SortExpression="ImageDescription" />
</Columns>
<RowStyle BackColor="#EFF3FB" Height="2em" />
</asp:GridView>