SQL Server entry using URL querystring - asp.net

I am getting a URL from PIC 32 controller using it's post function.
which is like, www.example.com/Default.aspx?x=12&y=23
What I want to do is that when I get the URL, I want to store the values of x and y into SQL Server.
I have launched a .aspx using the IIS server on my system. The coding of the aspx page is..
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Sample Configuration Page</title>
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td>IP Address:</td>
<td>
<asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>MAC Address:</td>
<td>
<asp:TextBox ID="TxtUserName" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</div>
<asp:Button ID="Button1" runat="server" Text="Save"
onclick="Button1_Click" />
</form>
</body>
</html>
Please guide me with this.
The data will be stored in the database with following C# code,
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO tblRegistration1 (IP, MAC) VALUES "
+ " (#IP_Address,#MAC_Address)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[6];
//param[0] = new SqlParameter("#id", SqlDbType.Int, 20);
param[0] = new SqlParameter("#IP_Address", SqlDbType.VarChar, 50);
param[1] = new SqlParameter("#MAC_Address", SqlDbType.VarChar, 50);
param[0].Value = IP_Address;
param[1].Value = MAC_Address;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
public string GetConnectionString()
{
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
}
Everything is fine while using it with the computer browser.
But the post coming from the PIC32 is not executing. I dont know how do i proceed with the URL coming back to my IIS server which contains IP and MAC details.
In my application I m having these data from PIC32 plat from as well computers.
I hope I have made my self clear.

To get a variable form URL use
Request.QueryString["variable"];
So you can use SqlDataSource to establish SQL Connection or SqlConnection
SqlDataSource
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString='<%$ ConnectionStrings:Conn %>'InsertCommand="INSERT INTO [TableName] ([x], [y]) VALUES (#x, #y)" >
<InsertParameters>
<asp:QueryStringParameter Name="x" Type="Int16"></asp:Parameter>
<asp:QueryStringParameter Name="y" Type="Int16"></asp:Parameter>
</InsertParameters>
</asp:SqlDataSource>
SqlConnection
public void insertData()
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO TableName(x, y) VALUES(#x, #y)", con))
{
cmd.Parameters.Add(new SqlParameter("x", Request.QueryString["x"]));
cmd.Parameters.Add(new SqlParameter("y", Request.QueryString["y"]));
cmd.ExecuteNonQuery();
}
}
catch (Exception Ex)
{
Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
}
}
}

Related

how to formate string of tree view

i have one tree view. i want to formate appended string like grid view:
<ItemTemplate>
<asp:Label ID="lbut_subject" runat="server"
Text='<%#Eval("Inquiry_subject").ToString().Length > 10 ? Eval("Inquiry_subject").ToString().Substring(0,10)+"..." :Eval("Inquiry_subject") %>'
ToolTip='<%# Bind("Inquiry_subject") %>'></asp:Label>
</ItemTemplate>
how ever i want this this to do with my tree view:
<asp:TreeView ID="TV_Question_Summary" runat="server" ImageSet="Simple" ShowLines="True" OnTreeNodeDataBound="TV_Question_Summary_DataBound" SkipLinkText="">
<DataBindings>
<asp:TreeNodeBinding DataMember="Root" FormatString=" {0}" TextField="" ValueField=""/>
<asp:TreeNodeBinding DataMember="ParentNode" FormatString=" {0}" TextField="Inquiry_id" ValueField="Inquiry_id"/><asp:TreeNodeBinding DataMember="Node" FormatString=" {0}" TextField="body" ValueField="Inquiry_id" ToolTip="body"/>
</DataBindings>
</asp:TreeView>
i want to string presentation like ... if Node filed body string gets overflow of no of 15 chars...
for binding up text i use this code:
void fill_Tree()
{
using (SqlConnection conn = Util.GetConnection())
{
conn.Open();
SqlCommand SqlCmd = new SqlCommand("Select * from tbl_Inquiry_History Where (IsDisplay='True')", conn);
SqlDataReader Sdr = SqlCmd.ExecuteReader();
SqlCmd.Dispose();
string[,] ParentNode = new string[100, 2];
int count = 0;
while (Sdr.Read())
{
ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("Inquiry_id")).ToString();
ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("Inquiry_id")).ToString();
}
Sdr.Close();
for (int loop = 0; loop < count; loop++)
{
TreeNode root = new TreeNode();
root.Text = ParentNode[loop, 1];
root.NavigateUrl = "~/Admin/OWM_Inquiry.aspx?inquiryid="+ ParentNode[loop, 1];
SqlCommand Module_SqlCmd = new SqlCommand("Select * from tbl_Question where (Inquiry_id = #parent_id AND IsCount='False')", conn);
Module_SqlCmd.Parameters.AddWithValue("#parent_id", ParentNode[loop, 0]);
SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader();
while (Module_Sdr.Read())
{
TreeNode child = new TreeNode();
child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("body")).ToString();
child.NavigateUrl = "~/Admin/OWM_Inquiry.aspx?inquiryid="+ParentNode[loop, 0];
root.ChildNodes.Add(child);
}
Module_Sdr.Close();
TV_Question_Summary.Nodes.Add(root);
}
TV_Question_Summary.CollapseAll();
}
}
please help me...
Try using a code-behind method instead of embedded code blocks, like this:
protected string DisplayInquirySubject(string inquirySubject)
{
return inquirySubject.Length > 10
? inquirySubject.Substring(0, 10)
: inquirySubject;
}
Now in your markup, you can call the method like this:
<ItemTemplate>
<asp:Label ID="lbut_subject" runat="server"
Text='<%# DisplayInquirySubject(Eval("Inquiry_subject").ToString()) %>'
ToolTip='<%# Bind("Inquiry_subject") %>'>
</asp:Label>
</ItemTemplate>
This has two benefits, it simplifies your markup logic and it allows you to leverage the power of the Visual Studio code editor (i.e. Intellisense and debugging).

Why can't I see ajax slide show images when I run?

I'd like to have an ajax slideshow on my web site. I get image urls from a database.
I think the code is right,but when I debug it my database photos are not shown.
I'm sure that my photos load completely.
<ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajax:ToolkitScriptManager>
<div align="center">
<asp:Image ID="imgslides" runat="server" Height="400px"
ImageUrl="Gallery images/72007_205.jpg" BorderColor="Black"
BorderStyle="Solid" BorderWidth="5 px" />
<asp:Button ID="btnPrevious" runat="server" Text="Prev" />
<asp:Button ID="btnPlay" runat="server" Text="Play" />
<asp:Button ID="btnNext" runat="server" Text="Next" />
<ajax:SlideShowExtender ID="SlideShowExtender1"
runat="server" AutoPlay="true" Loop="true"
NextButtonID="btnNext"
PreviousButtonID="btnPrevious"
PlayButtonID="btnPlay"
PlayButtonText="Play"
StopButtonText="Stop"
TargetControlID="imgslides"
SlideShowServiceMethod="GetSlides"
SlideShowServicePath = "Slideshow.asmx">
</ajax:SlideShowExtender>
and this is my web service code Slideshow.asmx
public AjaxControlToolkit.Slide[] GetSlides()
{
SqlConnection myconn = new SqlConnection();
myconn.ConnectionString = "Data Source=PARISA-PC;Initial Catalog=Images;Integrated Security=True";
myconn.Open();
string selectCmd = "select * from images";
string countCmd = "select count(*) from images";
SqlCommand myCmd = new SqlCommand(selectCmd,myconn);
SqlCommand myCmd2 = new SqlCommand(countCmd,myconn);
int i = 0;
SqlDataReader dr = myCmd.ExecuteReader();
ArrayList ar = new ArrayList();
try
{
while (dr.Read())
{
ar.Add(dr.GetString(2));
}
}
catch (Exception)
{
throw;
}
myconn.Close();
AjaxControlToolkit.Slide[] Photos = new AjaxControlToolkit.Slide[ar.Count];
for(i=0 ; i< ar.Count ; i++){
Photos[i] = new AjaxControlToolkit.Slide(ar[i].ToString(),"image"+i.ToString(),"Booth's images");
}
return Photos;
}
[1]: http://i.stack.imgur.com/eMw4S.jpg
You have to use http handler or an aspx page (which showing images from database). Then you can send the Query String to that handler or aspx for a particular image from ajax slide web service. You can get enough examples in google about it.

asp.net grid view hyper link pass values to new window

hai guys here is my question please help me
I have a gridview with hyperlink fields here my requirement is if I click on hyperlink of particular row I need to display that particular row values into other page in that page user will edit record values after that if he clicks on update button I need to update that record values and get back to previous home page. if iam clicking hyper link in first window new window should open with out any url tool bar and minimize close buttons like popup modular Ajax ModalPopUpExtender but iam un able to ge that that one please help me
the fillowing code is defalut.aspx
<head runat="server">
<title>PassGridviewRow values </title>
<style type="text/css">
#gvrecords tr.rowHover:hover
{
background-color:Yellow;
font-family:Arial;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="gvrecords" AutoGenerateColumns="false"
HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="White" DataKeyNames="UserId" RowStyle-CssClass="rowHover">
<Columns>
<asp:TemplateField HeaderText="Change Password" >
<ItemTemplate>
<a href ='<%#"UpdateGridviewvalues.aspx?UserId="+DataBinder.Eval(Container.DataItem,"UserId") %>'> <%#Eval("UserName") %> </a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Email" HeaderText="Email" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
following code default.aspx.cs code
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=.;Integrated Security=SSPI;Initial Catalog=testdb1");
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserDetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
con.Close();
DataSet ds = new DataSet();
da.Fill(ds);
gvrecords.DataSource = ds;
gvrecords.DataBind();
}
}
this is updategridviewvalues.aspx
<head runat="server">
<title>Update Gridview Row Values</title>
<script type="text/javascript">
function Showalert(username) {
alert(username + ' details updated successfully.');
if (alert) {
window.location = 'Default.aspx';
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td colspan="2" align="center">
<b> Edit User Details</b>
</td>
</tr>
<tr>
<td>
User Name:
</td>
<td>
<asp:Label ID="lblUsername" runat="server"/>
</td>
</tr>
<tr>
<td>
First Name:
</td>
<td>
<asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Last Name:
</td>
<td>
<asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Email:
</td>
<td>
<asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnUpdate" runat="server" Text="Update" onclick="btnUpdate_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" onclick="btnCancel_Click"/>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
and my updategridviewvalues.aspx.cs code is follows
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class UpdateGridviewvalues : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=.;Integrated Security=SSPI;Initial Catalog=testdb1");
private int userid=0;
protected void Page_Load(object sender, EventArgs e)
{
userid = Convert.ToInt32(Request.QueryString["UserId"].ToString());
if(!IsPostBack)
{
BindControlvalues();
}
}
private void BindControlvalues()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserDetails where UserId=" + userid, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
con.Close();
DataSet ds = new DataSet();
da.Fill(ds);
lblUsername.Text = ds.Tables[0].Rows[0][1].ToString();
txtfname.Text = ds.Tables[0].Rows[0][2].ToString();
txtlname.Text = ds.Tables[0].Rows[0][3].ToString();
txtemail.Text = ds.Tables[0].Rows[0][4].ToString();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("update UserDetails set FirstName='" + txtfname.Text + "',LastName='" + txtlname.Text + "',Email='" + txtemail.Text + "' where UserId=" + userid, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
int result= cmd.ExecuteNonQuery();
con.Close();
if(result==1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:Showalert('"+lblUsername.Text+"')", true);
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("~/Default.aspx");
}
}
My requirement is new window should come like pop window as new window with out having url and close button
my database tables is
ColumnName DataType
-------------------------------------------
UserId Int(set identity property=true)
UserName varchar(50)
FirstName varchar(50)
LastName varchar(50)
Email Varchar(50)
There are a host of options in the jQuery field:
jQueryUI's dialog
Wijmo's Dialog
SimpleModal
If you'd already using jQuery, jQueryUI's option may be a good fit. Wijmo is also jQueryUI compatible/friendly (use the same theme CSS class names and patterns), so it's also a good fit.
So it kind of depends on what you want. Something very simple - maybe jQueryUI. Flashy/pretty -- SimpleModal. More complex but jQueryUI-friendly - Wijmo.

.ExecuteNonQuery() sql asp.net error

This is my first time working with sql and asp.net. I am working on a few examples to ensure I have all the basics I need. I was walking though a tutorial and where everything should be working just fine, I am getting an .ExecuteNonQuery() Error. SqlException was unhandled by user code // Incorrect syntax near the keyword 'Table'.
If you have any pointers, let me know. I worked the tutorial twice, I'm sure I'm doing something wrong here. -Thanks
.CS Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace WebSite
{
public partial class _default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Table values('" + txtfName.Text + "','" + txtlName.Text + "','" + txtpNumber.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible = true;
Label1.Text = "Your DATA has been submitted";
txtpNumber.Text = "";
txtlName.Text = "";
txtfName.Text = "";
}
}
}
.aspx File:
<form id="form1" runat="server">
<div class="auto-style1">
<strong>Insert data into Database<br />
<br />
</strong>
</div>
<table align="center" class="auto-style2">
<tr>
<td class="auto-style3">First Name:</td>
<td class="auto-style4">
<asp:TextBox ID="txtfName" runat="server" Width="250px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">Last Name:</td>
<td class="auto-style4">
<asp:TextBox ID="txtlName" runat="server" Width="250px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">Phone Number:</td>
<td class="auto-style4">
<asp:TextBox ID="txtpNumber" runat="server" Width="250px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3"> </td>
<td class="auto-style4">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" Width="150px" />
</td>
</tr>
</table>
<br />
<br />
<asp:Label ID="Label1" runat="server" ForeColor="#663300" style="text-align: center" Visible="False"></asp:Label>
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Table]"></asp:SqlDataSource>
</form>
SQL Database:
CREATE TABLE [dbo].[Table] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[fName] VARCHAR (50) NOT NULL,
[lName] VARCHAR (50) NOT NULL,
[pNumber] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Usually this error message is caused by a single quote present in your input textboxes or by the use of a reserved keyword. Both problems are present in your query. The TABLE word is a reserved keyword for SQL Server and thus you should encapsulate it with square brackets, while for the possible presence of a single quote in the input text the correct approach is to use Parameterized Query like this
SqlCommand cmd = new SqlCommand("insert into [Table] values(#fnam, #lnam, #pNum)", con);
cmd.Parameters.AddWithValue("#fnam", txtfName.Text );
cmd.Parameters.AddWithValue("#lnam", txtlName.Text );
cmd.Parameters.AddWithValue("#pNum", txtpNumber.Text);
cmd.ExecuteNonQuery();
With this approach you shift the work to parse your input text to the framework code and you avoid problems with parsing text and Sql Injection
Also, I suggest to NOT USE a global variable to keep the SqlConnection reference. It is an expensive resource and, if you forget to close and dispose it, you could have a significant impact on the performance and the stability of your application.
For this kind of situations the using statement is all you really need
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString));
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into [Table] values(#fnam, #lnam, #pNum)", con);
cmd.Parameters.AddWithValue("#fnam", txtfName.Text );
cmd.Parameters.AddWithValue("#lnam", txtlName.Text );
cmd.Parameters.AddWithValue("#pNum", txtpNumber.Text);
cmd.ExecuteNonQuery();
}
Of course remove the global variable and the open in the Page_Load
Your query is trying to insert into a table called Table. Does that really exist? If not then put the actual table name into the query. If your table really is called Table then I strongly recommend you change it to something less confusing.
Also, stop writing commands by concatenating text now. Learn how to use parameters in order to prevent SQL injection
EDIT
An insert statement uses the format specified in the BOL documents for INSERT, and the examples provided therein. Table is a keyword, so don't use it as a table name. If you have to use a keyword, you need to escape it using square brackets. See BOL: Delimited Identifiers
I still say, don't use "Table" as the name for a table. Make your life easier.
Oh, and write secure code (see the above comment re SQL injection, and how Linked In got hit, and how much it cost them)
Changed 'insert into Table values' to 'insert into [Table] values' and all works fine. Thanks Note to self, stay away from simple names.
SqlConnection conn = new SqlConnection("Data Source=MCTX-ZAFEER\\SQLEXPRESS;Initial Catalog=ZKAbid_Db;Persist Security Info=True;User ID=sa;Password=sa#1234");
public int checkLogin(Ad_login ad)
{
SqlCommand cmd = new SqlCommand("Sp_Login", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Admin_id", ad.Ad_id);
cmd.Parameters.AddWithValue("#Password", ad.Ad_Password);
// cmd.InsertCommand.Connection = connection1;
SqlParameter objLogin = new SqlParameter();
objLogin.ParameterName = "#isValid";
objLogin.SqlDbType = SqlDbType.Bit;
objLogin.Direction = ParameterDirection.Output;
cmd.Parameters.Add(objLogin);
conn.Open();
cmd.ExecuteNonQuery();
int res = Convert.ToInt32(objLogin.Value);
conn.Close();
return res;
}
Wherever you are using ExecuteNonQuery() you should catch SqlException or you need to throws from your function.
In the case given above Button1_Click is the function using ExecuteNonQuery() from SqlCommand class.
Now what happens that this function ( ExecuteNonQuery ) has definition to throws SqlException. so you have two option
- you can also throws SqlException
- or you can put this line in try catch block to handle the Exception.

Get username in OnLoggedIn and update user in sql

I have a script in my site.master page that updates an SQL, it works fine as shown below, but instead of updating the Test I want to update the user who just logged in.
How do I select the current user?
I've found the following, but do not know if it's right, and where it should be added:
System.Web.HttpContext.Current.User.Identity.Name
I use Forms Authentication.
<script runat="server">
void OnLoggedIn(object sender, EventArgs e)
{
//connect to the db
SqlConnection conn = new SqlConnection(WebConfigurationManager.
ConnectionStrings["herning_brand_dk_dbConnectionString"].ConnectionString);
//the command to increment the value in the LoginCounter column by 1
SqlCommand cmd = new SqlCommand("UPDATE aspnet_Users SET
LoginCounter = LoginCounter+1 WHERE UserName = 'Test'", conn);
cmd.CommandType = CommandType.Text;
//update where UserName is Test
cmd.Parameters.AddWithValue("UserName", "Test");
using (conn)
{
//open the connection
conn.Open();
//send the query to increment the number
cmd.ExecuteNonQuery();
}
Label1.Text = System.Web.HttpContext.Current.User.Identity.Name;
}
</script>
EDIT
This works: (more or less)
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["herning_brand_dk_dbConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_Users SET LoginCounter = LoginCounter+1 WHERE UserName = #UserName", conn);
cmd.CommandType = CommandType.Text;
//update where UserName is x
cmd.Parameters.AddWithValue("UserName", Login1.UserName);
using (conn)
{
//open the connection
conn.Open();
//send the query to increment the number
cmd.ExecuteNonQuery();
}
It works with a fresh new Login control named "Login1".
But it does not work with the login control I have converted to template, even when I call it "Login1".
<asp:LoginView ID="LoginView1" runat="server">
<LoggedInTemplate>
<b>Velkommen: </b>
<asp:LoginName ID="LoginName1" runat="server" Font-Bold="True" Font-Size="Medium" /> <br />
<asp:LoginStatus ID="LoginStatus1" runat="server" LogoutText="Log ud" Font-Size="Small" LogoutPageUrl="~/Default.aspx" />
</LoggedInTemplate>
<AnonymousTemplate>
<asp:Login ID="Login1" OnLoggedIn="OnLoggedIn" runat="server">
<LayoutTemplate>
<table border="0" cellpadding="1" cellspacing="0" style="border-collapse:collapse;">
<tr>
.....
.....
Any suggestions why?
From the code snippet i would say that you use Login control for the forms authentication. As explained in this example on msdn you can get the username directly from the Login control itself.
Then, your code would look like this:
SqlCommand cmd = new SqlCommand("UPDATE aspnet_Users SET
LoginCounter = LoginCounter+1 WHERE UserName = #UserName", conn);
cmd.CommandType = CommandType.Text;
//update where UserName is Test
cmd.Parameters.AddWithValue("UserName", Login1.UserName);
where Login1 is the ID of your Login control. I'm not sure if you can use
System.Web.HttpContext.Current.User.Identity.Name
at this point because the authentication just occured on the PostBack and the Context is already initialized. I think you can use the User.Identity after the authentication Request is finished.
If you are using the Login control, what you want is this:
MembershipUser user = Membership.GetUser();
string username = user.UserName;

Resources