2014年7月13日 星期日

[RESOLVED] use session in other page


Hi 


i have index page which is the first page that will appear for user to chosse his country and i have used this session for it:


Session["location"] = worlddrdolist.SelectedItem.Value;

Response.Redirect("Berava.aspx");


And in the Master page i have add a imagebtn and i want to use this imagebtn to allow user when he click on it to return him to the page Berava.aspx depend on the session 


protected void logobtn_Click(object sender, ImageClickEventArgs e)

{

Response.Redirect("Index.aspx");



}


Any help with it :-)



If you are storing a value within the Session in one area as seen below :


// You may want to consider using the SelectedValue property as SelectedItem may not always exist
Session["location"] = worlddrdolist.SelectedValue;

Then within another page (either another ASPX page or your Master Page), you'll want to check and ensure that your Session value exists and then handle it accordingly :


// Check if your Location value exists
if(Session["location"] != null)
{
// It exists, so determine where to navigate based on your values
string location = Session["location"];

switch(location)
{
case "LocationA":
// Navigate accordingly
break;
case "LocationB":
// Navigate accordingly
break;
default:
// Navigate accordingly
break;
}
}



.



Hi Rion William


Thanks for your reply, but i am using one page which is Berava.aspx only and inside this page i have ListView that show the items of each country depend on the session thats mean havent create many pages for many countries. So the user when he write the
website URL Index.aspx will appear and he have to chosse his country and when he click on movebtn the server will redirect him to Berava.aspx and the ListView will show the items of his country. So what i want if the user in any other page to redirect him
to Berava.aspx that apear to him after he chosse his country



So you basically would want to check if a location has been selected and if not direct the user to the Index page to allow him or her to select one. If you wanted to handle this application-wide, you might consider adding the following within your Master
Page (this assumes that all of the areas of your application will use your Master Page) :


// Check if your Location Session doesn't exist
if(Session["Location"] == null)
{
// Redirect the user to the Index.aspx page
Response.Redirect("Index.aspx");
}

After he / she has selected a country within the Index page, you can then redirect them to the appropriate page based on your selection. Then with another page loads, you can pull the value of your Session and use it to populate the items within your ListView.



[RESOLVED] Checkbox


I have a single checkbox...however I want to store the value of the checkbox into the database instead of having it show on the page....


what would i change cbpb2.text to?


If cbpb2.Checked = True Then
cbpb2.Text = "Y"
Else
cbpb2.Text = "N"
End If



 



By value do you mean the state or the label of the CheckBox? 



state



You can use a bit field and then you write 1 to it if the CheckBox is checked, otherwise 0/null. So when you check the CheckBox and it's "checked" Update this column to 1 otherwise 0.


[RESOLVED] datetime format


i was working my projct in vs 2010 and now im transfering my project to vs2012


i have a date control which saves date in te format dd/mm/yyyy in the database.


when calling that date it's returning it as mm/dd/yyyy


i want a function that transforms the date retrieved from the database which is (dd/mm/yyyy) into the format (mm/dd/yyyy)


this is my control: 







this is my loading function:




private void LoadRuling(int RulingID, string language)

{


.


.


.

if (rul_entries.RulingDate != null)

{

txt_date1.GregorianDateText = obj_str.Entry(1, rul_entries.RulingDate.ToString(), ' ');

}


.


.


.


}


i have this function also:


public DateTime GregorianDate

{

get

{

if (txtDate.Text == "") return DateTime.MinValue;


DateTime selectedDate = DateTime.MinValue;

System.Globalization.CultureInfo format = new System.Globalization.CultureInfo("en-US");


try

{

selectedDate = DateTime.ParseExact(txtDate.Text, "dd/MM/yyyy", format);

}

catch

{

selectedDate = new DateTime();

}


return selectedDate;

}

set

{

if (value == DateTime.MinValue)

txtDate.Text = "";

else

txtDate.Text = value.ToString("dd/MM/yyyy");

}


public string GregorianDateText

{

get { return txtDate.Text; }

set { txtDate.Text = value; }

}




Dates in your database don't have a format, they represent a point in time.  Dates only have a format when you convert them to a string.  So get the date from the database as a DateTime class (not as a string) and use ToString when you want to display it


DateTime dtMyDate = (DateTime) somedatasource["SomeDateTimeField"]; // don't know how you're getting data from your database, change as needed


dtMyDate.ToString("MM/dd/yyyy");



String MyString = "30-12-2014"; 
DateTime MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "dd-MM-yyyy",null);
String MyString_new = MyDateTime.ToString("MM-dd-yyyy");

[RESOLVED] need review


hi guys


  Professional jQuery 
by wrox.   book for Jquery



kindly suggest . This book is good for beginners or not ???



In my case i found below book is better:


Beginning jQuery 2 for ASP.NET Developers


after that you need to read professional books.



that book u ve suggested i.e Beginning jQuery 2 for ASP.NET Developers: Using jQuery 2 with ASP.NET Web Forms and ASP.NET MVC  is giving
both webforms and MVC. i need only webform.



Start webform part from here than start reading professional books.



masters share your thoughts abt this book



While I can't specifically vouch for Wrox's jQuery book, I would recommend checking out the "12 Best Resources to Learn jQuery", which covers a wide variety of materials
such as walkthroughs, documentation and tutorials to get you started.



These are extensive tutorial series that range from beginner to advanced and I would argue one of the best ways to actually learn jQuery. Additionally, sites like
JSBin and JSFiddle
are excellent resources to get some practice in using jQuery from within your browser.


[RESOLVED] add dropdown and textboxes to a dictionary collection


Hello guys,


I am using the approach to be able to iterate through the textboxes and dropdow list on a page



public static IEnumerable GetAllControls(Control parent)
{
if(null == parent) return null;

return new Control[] { parent }.Union(parent.Controls.OfType().SelectMany(child => GetAllControls(child));
}



foreach(DropDownList list in GetAllControls(this).OfType())
{
//TODO: add values to dictionary collections and append to session object
}

Now, after the loop and getting the values, I need to be able to store the droplist list ids and values into a sesion to be available elsewhere in the application.


Please help.



Thanks



untested, but something like


Dictionary data = new Dictionary();

foreach(DropDownList list in GetAllControls(this).OfType())
{
data.Add (list.ID, list.Items);
}

Session["DropDownData"] = data;


[RESOLVED] Active Directory update


I have a process for users to update inofrmation in Ad, one of the things I never accounted for was last name change.  I am trying to change the CN but it keeps erroring me out and tried to search for information but have not been able to find anything. 
Does anyone know how to update the CN of an Active Directory account.  It does not like the remaning of the CN, others said this should work but does not seem to work for me.


Here is my code.


 


  myDataTable = New DataTable
myDataTable = getData(sql)

'Build the Cn
cn = myDataTable.Rows(0)(3).ToString() & "\, " & myDataTable.Rows(0)(17).ToString()

If myDataTable(0)(11) <> "" Then
phone = myDataTable(0)(11)
Else
phone = " "
End If

If myDataTable(0)(12) <> "" Then
ip = myDataTable(0)(12)
Else
ip = " "
End If

Try
user.Properties("employeeType").Value = myDataTable(0)(0).ToString()
user.Properties("mail").Value = myDataTable(0)(1).ToString()
user.Properties("displayName").Value = myDataTable(0)(2).ToString()
user.Properties("sn").Value = myDataTable(0)(3).ToString()
user.Properties("personalTitle").Value = myDataTable(0)(4).ToString()
user.Properties("title").Value = myDataTable(0)(5).ToString()
user.Properties("department").Value = myDataTable(0)(6).ToString()
user.Properties("l").Value = myDataTable(0)(7).ToString()
user.Properties("streetAddress").Value = myDataTable(0)(8).ToString()
user.Properties("st").Value = myDataTable(0)(9).ToString()
user.Properties("postalCode").Value = myDataTable(0)(10)
user.Properties("telephoneNumber").Value = phone.ToString()
user.Properties("ipPhone").Value = ip.ToString
user.Properties("physicalDeliveryOfficeName").Value = myDataTable.Rows(0)(13).ToString()
user.Properties("extensionAttribute2").Value = myDataTable.Rows(0)(14).ToString()
user.Properties("comment").Value = myDataTable.Rows(0)(15).ToString()
user.Properties("description").Value = myDataTable.Rows(0)(16).ToString()
user.CommitChanges()
'user.Rename("CN=" & cn)
'user.CommitChanges()

Return True
Catch ex As Exception
Return False
End Try

user.Close()
End If
dirEntry.Close()



I don't think you should need the domain here.  Assuming that column 17 is the user name then it would be:


User.Rename("CN=" + myDataTable.Rows(0)(17).ToString())






HI, that is not the domain, it is the last name and then I add some other data to it.  Here is the error I receive.


 


A device attached to the system is not functioning.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.DirectoryServices.DirectoryServicesCOMException: A device attached to the system is not functioning.


Source Error:
Line 320: user.Properties("description").Value = myDataTable.Rows(0)(16).ToString()
Line 321: user.CommitChanges()
Line 322: user.Rename("CN=" + cn)
Line 323: 'user.CommitChanges()
Line 324: ' End With

Source File: C:\inetpub\wwwroot\iMAC\App_Code\iMACAD.vb Line: 322

Stack Trace:


[DirectoryServicesCOMException (0x8007001f): A device attached to the system is not functioning.
]
System.DirectoryServices.DirectoryEntry.MoveTo(DirectoryEntry newParent, String newName) +335
System.DirectoryServices.DirectoryEntry.Rename(String newName) +44
iMACAD.UpdateADUser(String samAccount, Int32 userId) in C:\inetpub\wwwroot\iMAC\App_Code\iMACAD.vb:322
Admin_MacRequests.lnkSubmit_Click(Object sender, EventArgs e) in C:\inetpub\wwwroot\iMAC\Admin\MacRequests.aspx.vb:366
System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +116
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +101
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +9528578
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724




Oh....  I have pretty much the same code but I don't have the / in my names.  Perhaps you need to escape it: //  or try a different character.



HI I don't either I thought the / was the escape to get the comma puit in between last and first names.


Doe, John H MN NG FTS



Did you try without it?



found out i can conetacting and extra comma that i was not escaping in my datarow.  Guess I should hve checked the data before starting a fuss.


[RESOLVED] SqlCommand and SqlConnection dispose


I am using code below to open and dispose connection.


     -----------------------


       Dim mySQLCommand As New SqlCommand("sp_addorder", myConn)


        mySQLCommand.CommandType = CommandType.StoredProcedure


        -----


         Using myConn


            Try


                myConn.Open()


                mySQLCommand.ExecuteNonQuery()


                myConn.Close()


              Catch ex As SqlException


           Finally


                myConn.Dispose()


            End Try


        End Using


---------------------------------


Do I need to do more before disposing, like



  1. Check to see if the object exists before calling the dispose method
  2. The mySQLCommand should also be disposed of

       



This may help you determine how to best handle that:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2


 


I would presume just check that myConn and mySQLCommand are not null and if they aren't, dispose



You could check it isn't nothing first for completeness, but there is no way it can be nothing in the finally block.  You don't need to dispose the sqlcommand.



Exactly why I provided the op with that link :)



I was replying at the same time, I didn't see your reply until I posted :)



Ah that's true :)  That is what I sometimes will do is provide a link so the poster can see it in action written a bit more eloquently than I can.



You might try wrapping both your Connection and your Command within Using statements :


' Establish your connection '
Using myConn
Try
' Define your command to execute '
Using mySQLCommand As New SqlCommand("sp_addorder", myConn)
' Open your connection '
myConn.Open()

' Indicate this command is a stored procedure '
mySQLCommand.CommandType = CommandType.StoredProcedure

' Execute your query '
mySQLCommand.ExecuteNonQuery()
End Using
Catch ex As SqlException
' Do something here if an error occurs '
End Try
End Using

The Using statement will take care of closing and disposing any open connections that you have so you don't need to worry about it manually (via a Finally statement). If you take a look at the
documentation for the using statement, you'll see that it actually compiles into a try-catch-finally statement.



I like that Rion, very clean and efficient.  I trust this also would apply to c# correct?





bbcompent1


I like that Rion, very clean and efficient.  I trust this also would apply to c# correct?


Correct.


A C# equivalent would look something like :


//Establish your connection
using(var sqlConnection = new SqlConnection("Your Connection String"))
{
try
{
// Define your command to execute
using(var sqlCommand = new SqlCommand("sp_addorder", sqlConnection))
{
// Open your connection
sqlConnection.Open();

// Indicate this command is a stored procedure
sqlCommand.CommandType = CommandType.StoredProcedure;

// Execute your query
sqlCommand.ExecuteNonQuery();
}
}
catch(SqlException ex)
{
// Do something here if an error occurs
}
}





Rion Williams



You might try wrapping both your Connection and your Command within Using statements :


' Establish your connection '
Using myConn
Try
' Define your command to execute '
Using mySQLCommand As New SqlCommand("sp_addorder", myConn)
' Open your connection '
myConn.Open()

' Indicate this command is a stored procedure '
mySQLCommand.CommandType = CommandType.StoredProcedure

' Execute your query '
mySQLCommand.ExecuteNonQuery()
End Using
Catch ex As SqlException
' Do something here if an error occurs '
End Try
End Using

The Using statement will take care of closing and disposing any open connections that you have so you don't need to worry about it manually (via a Finally statement). If you take a look at the
documentation for the using statement, you'll see that it actually compiles into a try-catch-finally statement.





If you're doing your own try catch there isn't much point in using "using", you might as well implement your own finally.





AidyF


If you're doing your own try catch there isn't much point in using "using", you might as well implement your own finally.


That's a good point AidyF. I was just demonstrating that a using could be used here with regards to worry about resource disposal in particular. It all depends on how OP plans to use the catch section.


[RESOLVED] User Login????


i have four pages asp.net (c#)


(1) Login Page (2) MainMenu1   (3) MainMenu2 (4) MainMenu3


i also have sql database name "mydatabase" have three tables 


(1) Student (2) Teacher   (3) Admin


Login page contain 2 textboxes (  textbox1 for username,  textbox2 for password) and login button


i want when login button is pressed then check (match) username and password in three tables (Student ,Teacher ,Admin)


*if user is Student then page MainMenu1 is open


*if user is Teacher then page MainMenu2 is open


*if user is Admin then page MainMenu3 is open


plzzzzzz help me?????



Ok, post your code.  I think it would be nothing more than code behind visibility statements based on


if (!User.IsInRole == "Student") 
{
Menu1.Visibility = hidden;
}
else
{
Menu1.Visibility = visible;
}



At what stage are you?  Are you in the process of setting up the databases / tables? Or are you having to work with pre-existing tables?


Because if you are just starting, then the suggestion of bbcompent1 is a slick way to do it.  When each user is created, you would want a bit of code-behind to assign that user to one of the three Roles.


Then you probably only only need the tables that come with the asp.net membership, no need to add separate tables for the students, teachers, and admin.


And you only need one page for the menus -- not three -- just showing or hiding them as suggested.


[RESOLVED] How to write a code for LastLogin Date &amp; Time


Hi all, im doing a project that requires a LastLogin Date & Time that can be seen whenever a user logs on to the system. Currently im using manual codes. Can any1 guide me on codes to make it automatically detect lastlogin?


Below are my initial codes



Thanks



Hello ,


How you are maintaining a login ? i mean are you using any authentication techniques ?



If you are using aspnet membership table for user management and authenticate user then there is already "LastLoginDate" column in "aspnet_Membership" table. save that date in session before authenticate user and use that date. Afret authentication LastLoginDate
will be updated.


And if you are not using membership table then you have to create a table which cane store date and time of login.



Tthanks everyone for trying to help me with my problems. I've managed to seek help around and solved it !


[RESOLVED] QueryString Question


Does this look ok to use? I'm trying to make sure there is nothing in the hidden field and txt boxes prior to making the request fro the querystrings.


I have this in my page load event


        If Not Page.IsPostBack Then
'clear all fields here then set them below, just to be sure they start out blank.
hfClient_ID.Value = DBNull.Value.ToString
hfAccount_ID.Value = DBNull.Value.ToString
hfEmail.Value = DBNull.Value.ToString
hfEmail.Value = DBNull.Value.ToString
txtFirstName.Text = ""
txtLastName.Text = ""
'load fields for the Client
hfClient_ID.Value = Request.QueryString("Client_ID")
hfAccount_ID.Value = Request.QueryString("Account_ID")
hfEmail.Value = Request.QueryString("Email")
txtEmail.Text = hfEmail.Value
txtFirstName.Text = Request.QueryString("FirstName")
txtLastName.Text = Request.QueryString("LastName")



On initial load of the page the controls will be empty, no? What I'm saying, there's no need for the clear part. 



You don't need to check it at first load, it's already blank



Below is a sample hiddenfield that already has a value at first load



You only need to check the query string to avoid error


If Request.QueryString("Client_ID") IsNot Nothing Then

hfClient_ID.Value = Request.QueryString("Client_ID")

End If


[RESOLVED] How to set function for searching website content?


Hey friends when website has huge posts , contains , stuff so usually you see there is search box where user will type whatever they wanna search on website and according to his search , related contents use to display on page so how to do it ??



It depends where your site gets its data from.  If it is a sql server then use Free Text searching to search for text in your fields and show the results as neccessary.  You might also want to look into Lucene which is an indexing technology you can plug
into various things (including SQL Server I believe).  If your site is just text files or content in aspx files then you'll need something that can index your site and give you a search interface - google do products that do this, and there will be many others
that do this too.  There is no single answer to this, it depends how your site is constructed and where the data comes from.



Hi,


If the website contents is stored on a database, you will need to create a query that searches the fields of the tables that store the content that you want to search. Ex:




SELECT MyTable1.ContentId AS ContentID, MyTable1.Title AS ContentTitle
FROM MyTable1
WHERE MyTable1.MyFieldToSearch1 LIKE '%' + @MySearchString + '%'

UNION ALL

SELECT MyTable2.ContentId AS ContentID, MyTable2.Title AS ContentTitle
FROM MyTable2
WHERE MyTable2.MyFieldToSearch2 LIKE '%' + @MySearchString + '%'


UNION ALL

SELECT MyTable3.ContentId AS ContentID, MyTable3.Title AS ContentTitle
FROM MyTable3
WHERE MyTable3.MyFieldToSearch3 LIKE '%' + @MySearchString + '%'

...

Then you need to call this query either by placing it as StoredProcedure (if the database engine allows it.  MS SQL Server does, but MS Access doesn't, for instance) or by writing it on the codepage/class and calling it.



Hope this helps,



Obe



You can integrate google search for your website.



Hi,




SACHIN2708


Hey friends when website has huge posts , contains , stuff so usually you see there is search box where user will type whatever they wanna search on website and according to his search , related contents use to display on page so how to do it ??


As AidyF suggested depends on different factors. Apart from the suggestions from other members below are few articles that you might find useful:


" This article describes a simple, free, easy to install Search page written in C#. The goal is to build a simple search tool that can be installed simply by placing three files on a website, and that could be easily extended to add all the features
you might need for a local-site search engine.


There are two main parts to a Search engine:



  • the build process, which processes files, indexing their contents and creating the 'catalog'.
  • the search process, which uses the 'catalog' to find the search term and the names of the files it appears in.  "

Source Article -
http://www.codeproject.com/Articles/7579/Static-Site-Search-Engine-with-ASP-NET-C


Creating an ASP.NET Search Engine -
http://www.developerfusion.com/article/4389/create-a-site-search-engine-in-aspnet/


Adding a Search Method and Search View -http://www.asp.net/mvc/tutorials/mvc-5/introduction/adding-search (MVC App)


Hope you find the information useful!


Best Regards!



[RESOLVED] How accept email format in asp.net?


Accept valid email format in asp.net


I am using following code



But this one 


I am enter data Anil@gmail.hhh this one also Accepting,It can accept only
Anil@gmail.com format



Hello Anil,


Try below regex expression, assuming you want only gmail account validation


^\w+([-+.']\w+)*@(?:GMAIL|gmail).com



i want all address



Let me tell you one thing, no matter what you do , end user can send invalid email ID.You can go through below reference for types of regex expressions , but then again , some loophole will be there:


http://regexlib.com/Search.aspx?k=email&AspxAutoDetectCookieSupport=1




Hi,




ANILBABU


i want all address


I agree with Asim there are thousands of domain and sub-domain now. Not possible to validate each and everyone of them.


Regards!


[RESOLVED] The data source does not support server-side data paging




When is AllowPaging ="False"  work fine!



Hello,


DataReaders doesn't support pagging, why ?DataReader is forward-only. Server-side Paging needs to be able to travel the datasource both backward and forward.So dont pass cmd.ExecuteReader directly to the datasource.Instead First load the reader
result to a datatable and then pass the datatable as datasource.


DataTable dt=new DataTable();
dt.Load(cmd.ExecuteReader());

gvBuyer.DataSource=dt;
gvBuyer.DataBind();

Hope This Helps.


[RESOLVED] Code to retrieve the Windows user id is not working in server


I have used the below code to retrieve the Windows user id of the system.


The code works well in my machine but when I deployed in Server it's not working as expected.


string[] authenticatedUserName;
System.Security.Principal.IPrincipal User;

User = System.Web.HttpContext.Current.User;

if (User.Identity.IsAuthenticated)
{
authenticatedUserName = User.Identity.Name.Split('\\');
string userName = authenticatedUserName[1].ToString();
}

Kindly help me to sort this issue



Windows auth only works when client and server are on the same domain, it's probably not working as you're doing it over the internet.



Hi AidyF


Thanks for your response.


I am working on the same domain and it's a intranet not internet.


But still there is a problem to read the windows user id.



Do the usual checks that anonymous access isn't enabled.



Hi AidyF,


I tried enabled the anonymous access in IIS but it throws me below error


401 - Unauthorized: Access is denied due to invalid credentials.


You do not have permission to view this directory or page using the credentials that you supplied.





dj_naveen



401 - Unauthorized: Access is denied due to invalid credentials.


You do not have permission to view this directory or page using the credentials that you supplied.





Hi,


According to your error message, I think you should reset you IIS. Please refer to the steps below:


1. Open iis and select the website that is causing the 401

2. Open the “Authentication” property under the “IIS” header

3. Click the “Windows Authentication” item and click “Providers”

4. Move NTLM at top and BAM that's fixed it.


There are some similar threads, please refer to the links below:


http://social.technet.microsoft.com/Forums/windowsserver/en-US/c9239a89-fbee-4adc-b72f-7a6a9648331f/401-unauthorized-access-is-denied-due-to-invalid-credentials?forum=winserversecurity


http://www.somacon.com/p581.php


Hope it's useful for you.


Best Regards,


Michelle Ge



[RESOLVED] How to do Update Profle page using , I am facing some problem please help.


Sir after login I come on profile page where information is showing like :


First Name: Sachin


Last Name : Agarwal


but it is not editable you can just see  and information is loading from database so now if you want to edit this information so I create one button Edit on same page when someone will click on edit button so new page will be open and I did coding in its
CS page in void Page_Load(object sender, EventArgs e)


  SqlConnection con = new SqlConnection(@"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=Chitrakala;Integrated Security=True");

        con.Open();

        String id = Session["uname"].ToString();

        string query = ("select* from Artist where User_Name='" + id + "'");

        SqlCommand cmd = new SqlCommand(query, con);

        SqlDataAdapter adpt = new SqlDataAdapter(cmd);

        DataTable dt = new DataTable();

        adpt.Fill(dt);



        tb1.Text = dt.Rows[0]["First_Name"].ToString();

        tb2.Text = dt.Rows[0]["Last_Name"].ToString();

        con.Close();


in above coding Artist is my table name and First_Name" and Last_Name is field name in table so due to this coding when some one will click on edit button so information is loading in text box from database :


First Name: Sachin


Last Name : Agarwal


but now it is editable means if I want to change last name so I use backspace to remove Agarwal and write new name .


 now I created A save button on this page and on Save button I did this coding:


 SqlConnection con = new SqlConnection(@"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=Chitrakala;Integrated Security=True");

        con.Open();

       

       String B = tb2.Text;

       String A = tb1.Text;

       

      string id= Session["uname"].ToString();





      string query = "update Artist set Last_name=('" + B + "') where User_Name='" + id + "'";



        SqlCommand cmd = new SqlCommand(query, con);

        cmd.ExecuteNonQuery();

        con.Close();



        Response.Redirect("Customer profile.aspx");


above query is update means after change it will redirect me to previous page means profile page but problem is Change is not done after click on Save button it is redirecting me on Profile page but no changes in Last name , still Agarwal is showing as Last
name so where is problem


Please help.



If you press ctrl+F5 do you see the updated information?



what ??? I am creating website and I am facing this error that Profile is not update please read full question my friend I need your help.



Hi,


According to your description and your code, first, the redirect did not redirect to Customer profile.aspx page, I suggest you check the path is correct. If the Customer profile.aspx page did not exist in the same level with profile.aspx page, please refer
to the code beow to redirect:


Response.Redirect("../Foloder/Customer profile.aspx");

Second I suggest you checking the updating, we should make sure the data in the DataBase, if the data in DataBase did not been updated, I suggest you making some break points to debug steps by steps. We should make sure the connections is connect right,
then we need check updating in the SQL database.


Third, after we redirect to Customer profile.aspx page, we should make sure we will bind new data to the page.


I searched an artical about update in profile, please refer to the link below:


http://asp-net-example.blogspot.com/2009/02/how-to-update-profile-in-aspnet.html


Hope it's useful for you.


Best Regards,


Michelle Ge


[RESOLVED] Create content Management System for ASP.net Website


I have a project in which I have to create some roles like admin and users and have to provide them permissions accordingly. Admin can edit and add webpages to a website.


I think I can achieve this from CMS. So can anyone help me as how can I do this???



Many thanks in advance



If I was you I'd look at some ready-made CMS solutions like Orchard or Umbraco.



Hi,


According to your description, you want to create a content management system. There is a demo, please refer to the link below:


http://evonet.com.au/creating-a-content-management-system-for-your-asp-net-web-site/


If you only want admin to edit the web pages, I think you should make roles, then as we want to edit the web pages, we can check by the roles.


For more information about CMS, please refer to the links below:


http://www.codeproject.com/Questions/260199/Creating-Content-Management-System-for-ASP-NET


http://n2cms.com/#tab2


Hope it's useful for you.


Best Regards,


Michelle Ge


[RESOLVED] How Can we Comments function on website


You see many website where Users can post their comments on web page like You tube and many others website have this function , and along with their comments also display their name and timing how I can do ?



There are two ways for implementing this:


1. Create a custom comment.


2. Integrate the other comment providers like facebook, google comment etc.





Please help me how to do ? I dont know about these what you told me.



Hi,




SACHIN2708


You see many website where Users can post their comments on web page like You tube and many others website have this function , and along with their comments also display their name and timing how I can do ?


There are different ways to get it done. Below are few articles that you might find useful.


Using Knockout.js :


Demo -
http://demo.techbrij.com/1119/facebook-wall-post-comment-knockout.php


Tutorial -
http://techbrij.com/facebook-wall-posts-comments-knockout-aspnet-webapi


Using Repeater Control : Tutorial  -http://dotprogramming.blogspot.com/2013/07/how-to-make-comment-box-in-aspnet.html


ASP.NET Forums Website Part 6 Add the New Comment Page  :
http://www.aspnettutorials.com/tutorials/advanced/forums-site-p6-asp4/


Hope it helps!


Best Regards!


[RESOLVED] Custom values in kendo grid &quot;Items per page&quot; dropdown


Hi, I have a kendo grid with several 1000's of rows. I want to display them as 1000 per page. Can any one please tell me how can I make the dropdown customized with the values like 1000, 5000, 10000 etc. and display number of rows based on it in javascript
or JQuery.



Any help appreciated!



Hi,


According to your description, you want to page the kendo Grid control and the pagesize comes from the DropDownList control's selected value. So far as I know, if we want to set 1000,5000,10000 as the datasource of the DropDownList control, please refer
to the code below:


$("#parent").kendoDropDownList({
dataTextField: "PageSize",
dataValueField: "SizeValue",
dataSource: [
{ PageSize: "Size1", parentId: 1000 },
{ PageSize: "Size2", parentId: 5000 },
{ PageSize: "Size3", parentId: 10000 },
]
});

For more information about kendoDropDownList, please refer to the link below:


http://docs.telerik.com/kendo-ui/api/web/dropdownlist


If you want to page the kendo Grid, please refer to the code below:


$("#parent").kendoDropDownList({
dataTextField: "PageSize",
dataValueField: "SizeValue",
dataSource: [
{ PageSize: "Size1", parentId: 1000 },
{ PageSize: "Size2", parentId: 5000 },
{ PageSize: "Size3", parentId: 10000 },
],
change: function(e) {
var grid = $("#grid").data("kendoGrid");
grid.dataSource.pageSize(parseInt(this.value())); // this.value() being the value selected in Combo
}

});

For more professional support, please refer to kendo forum as below link:


http://www.telerik.com/forums


Hope it's useful for you.


Best Regards,


Michelle Ge




Thanku Michelle!. But I found the solution..


I used:


pageable: {
pageSize: 1000,
pageSizes: [1000, 5000, 10000]
}


Hi,


Can we create Kendo ui grid fields on condition- like if the mode==1 then there shud be 4 field else there shud be 6 fields?



[RESOLVED] Fliter


i fliter gridview


using textbox and serach button


SP:



"SELECT * FROM [addproject1] WHERE ([ProjectName] LIKE '%' + @ProjectName + '%')">


but how write textbox to SP





sudharsan perumal



fliter gridview


using textbox and serach button


SP:



"SELECT * FROM [addproject1] WHERE ([ProjectName] LIKE '%' + @ProjectName + '%')">


but how write textbox to SP





Like this


string conString = ConfigurationManager.ConnectionStrings["MyCon"].ToString(); //Give your connection string here
SqlConnection sqlcon = new SqlConnection(conString);
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
String query;
if(txtsearch.Text!="")
query = "SELECT * FROM [addproject1] WHERE ([ProjectName] LIKE '%'" + txtsearch.Text + "%'";
}
sqlcmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
Gridview1.Source=dt;
GridView1.DataBind();


they come search button code?





sudharsan perumal


they come search button code?


Yes,you should write that code in the search button click event..query the database with the textbox value and bind your gridview.



Hi 


Create stored procedure:


CREATE PROCEDURE searchGrid
@ProjectName NVARCHAR(100)
AS
SELECT * FROM [addproject1] WHERE [ProjectName] LIKE '%' + @ProjectName + '%'

Codebehind: Write this on button click


string conString = ConfigurationManager.ConnectionStrings["MyCon"].ToString();
SqlConnection sqlcon = new SqlConnection(conString);
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
sqlcmd = new SqlCommand("searchGrid", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("@ProjectName", "ValueFromTextBox");
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
Gridview1.Source=dt;
GridView1.DataBind();



protected void Button1_Click(object sender, EventArgs e)

{

SqlConnection con = new SqlConnection("Data Source=DASATML-PC;Initial Catalog=sudharsan;Integrated Security=True");

//String query;

if (TextBox14.Text != "")

{

SqlCommand cmd = new SqlCommand("SELECT * FROM [addproject1] WHERE ([ProjectName] LIKE '%'" + TextBox14.Text + "%'", con);

DataTable dt = new DataTable();


con.Open();

SqlDataAdapter da = new SqlDataAdapter(cmd);

con.Close();

dt.Clear();

da.Fill(dt);                                                                        ERROR:Incorrect syntax near 'java'.

Unclosed quotation mark after the character string        





GridView1.DataSource = dt;

GridView1.DataBind();

}

}


[RESOLVED] master detail data entry


I want to create
input data for
order
and order
detail
,


Could you
give an example using asp.net (C#). 


in ASP.NET not MVC


order :

orderno  nvarchar(20)

orderdate datetime

customer nvarchar(20)

total decimal(18,2)



order_detail

id int (auto increament)

orderno nvarchar(20)

itemno nvarchar(20)

qty decimal(10,2)

price decimal(10,2)

total decimal(10,2)



item

itemno nvarchar (20)

itemname nvarchar(100)

price (10,2)



Hi,


I wrote this article some years ago, but it might still be valid.  I still do like jQuery.


http://www.thebestcsharpprogrammerintheworld.com/blogs/linq-to-nhibernate-jquery-jqgrid-subgrid-hql-and-icriteria.aspx


HTH, Benjamin



Refer full code
here
 and here


[RESOLVED] Finding a duplicate in a datatable, but excluding a row


How do I find a row in the datatable, and verified that the 'ID' is unique, but exclude the row that is being verified?


The Datatable in the code pulls all the rows, and it is finding all the rows for a duplicate ID. But I need it to exclude the row being verifity for that ID. How can I exclude it?




if (ID.Text != Dataset.Tables[0].Rows[0]["ID"].ToString())
{
string ID = "";
ID = ID.Text.ToString();

DataRow[] findrow = Datatable.Select("ID = '" + ID + "' ");

string findID = "";

foreach (DataRow row in findrow)
{
findID = row["ID"].ToString();
}

if (findID.ToString() == ID.ToString())
{
divError.Style.Add("visibility", "visible");
divError.Style.Add("display", "");
divError.Style.Add("top", "120%");
divError.Style.Add("left", "50%");
divError.Style.Add("margin-top", "-9em");
divError.Style.Add("margin-left", "-12em");
}

}



1. If its not possible to get distinct records, then get a new column which will have distinct value for each row e.g. autoincrement. This you can achieve in DB query or at code level. 


2. Get list of duplicates using LINQ and attached distinct value using min/max;


3. Use LINQ Outer join with step 2 output using distinct value as JOIN column




 


[RESOLVED] Access ApplicationUser property from site.master


Hi:


I have a webforms application using ASP.NET Identity 2, and I'm trying to show a custom property from ApplicationUser instead of Context.User.Identiy.GetUsername() in the login menu on the NavBar of the pages that are generated by site.master.


I'd greatly appreciate some hints how to get to my custom properties of the ApplicationUser object from wihin Site.Master to do this.



THANKS


Cheers -alex







Hi,


According to your description, you want to display the custom property for ApplicationUser. So far as I know, we need to take your custom properties that are already being passed in the SignInAsync() method via the user parameter and save them as "claims"
on the identity object.


private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim("FullName", user.FullName));
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

Second, you need to write an extention class for the User object.


There is a similar thread, please refer to the link below:


http://forums.asp.net/t/1957500.aspx?How+to+access+custom+Identity+or+ApplicationUser+properties+


Hope it's useful for you.


Best Regards,


Michelle Ge



Thanks Michelle, I'll give that a shot. I think the extension is most likely the way to go, as I already have the properties in the local user database, just need to find a way to get to it from the site.master.


Cheers -alex




Michelle:



THANKS so much. Works perfectly!



Cheers -alex



[RESOLVED] Render a Control into string at WebServices


Hi there,


I am trying to render the content of a control into a string while requesting a webservice.


I was already trying some different ways. Some returned an empty string and one throws an exception. Experimentaly I tried to place the content into a Page and get the Panel to render it but the page said it had no controls at all.


The way(which I was trying very hopefully) with the exception I have mentioned is the following


ImageElement ie = (ImageElement)new Page().LoadControl("~/Controls/ImageElement.ascx");

and it says something like ""Galerie.Controls.ImageElement"
is not allowed here
because the class
"System.Web.UI.UserControl"
is not expanded.
" (original in german is says: "Galerie.Controls.ImageElement" ist hier nicht zulassig, da die Klasse "System.Web.UI.UserControl" nicht erweitert wird.)


Init a new instance by new ImageElement(); always returns an empty string, even if it is a modified render-method or not.


Creating a new Page by new Page(); and insert a new Form with an inserted ImageElement-Object did not the job either.


What have I to do get the render-string? Is it a bit tricky because I am working in a werbservice? Is there maybe  a property to set at the beginning of the webservice-method?



Thank you!!



Create a new class


public class FormlessPage : System.Web.UI.Page
{
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
}
}

Your webservice method


[WebMethod]
public void RenderControl()
{
FormlessPage p = new FormlessPage();
MyUserControl c = (MyUserControl) new System.Web.UI.Page().LoadControl("~/MyUserControl.ascx");
p.Controls.Add(c);
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter w = new System.Web.UI.HtmlTextWriter(sw);
HttpContext.Current.Server.Execute(p, w, false);
string html = sw.ToString();

However from the error message you're getting, I think the issue is that your ImageElement.ascx does not derive from UserControl.  It's definition must be something like


public partial class MyUserControl : System.Web.UI.UserControl




Hey, thanks for the reply. I have tried this kind of solution already, but tried yours again. But no success with it too. It throws the exception on the same place as before. The ImageElement derives already from the UserControl, it has the following declaration:


public partial class ImageElement : System.Web.UI.UserControl

Currently I do not have any idea...




I think i did it.



The problem was the namespace - I need to set the same namespace for the ImageElement as for the UserControl (System.Web.UI).


[RESOLVED] changing div css class in user control from parent page


i have a page, that has a button on it that changes the css of the page, amending the layout.


because of the layout change, i also want to switch a user control on the page from a horizontal to a vertical layout. 


the div in the user control is set up as follows



and the code behind loads the control and places it in a placeholder.


when the button is pressed to switch the css of the parent page, my code clears the control and places it elsewhere. i then want to find the div and style it. 


my code behind for that is:


plcBrandTop.Controls.Clear();
plcBrandHead.Controls.Clear();
plcLeftArea.Controls.Clear();
Control branding = (Control)Page.LoadControl("~/ContentControls/BrandContainer.ascx");//loads brand control
Control menu = (Control)Page.LoadControl("~/ContentControls/VerticalMenu.ascx");//loads menu control (vertical)
Control socialmedia = (Control)Page.LoadControl("~/ContentControls/SocialMediaBar.ascx");//loads social media links
plcBrandHead.Controls.Add(branding);
plcLeftArea.Controls.Add(menu);
plcLeftArea.Controls.Add(socialmedia);
HtmlGenericControl ctrlSocialMedia = this.Page.FindControl("SocialMediaBar") as HtmlGenericControl;
ctrlSocialMedia.Attributes["class"] = "vertical";

But it is returning an error. I have checked and the problem is ctrlSocialMedia is Null - i.e. it is not finding the "SocialMediaBar" div in the user control.


any suggesttions as to how i can find it/access it?





dcgate


my code clears the control and places it elsewhere


How are you doing this and in which event?



on the button click (button is in the parent page) - in the code above, i first clear all the existing controls (because once the layout changes, some needs to be moved)


            plcBrandTop.Controls.Clear();
plcBrandHead.Controls.Clear();
plcLeftArea.Controls.Clear();

then reload and add the required controls 


            Control branding = (Control)Page.LoadControl("~/ContentControls/BrandContainer.ascx");//loads brand control
Control menu = (Control)Page.LoadControl("~/ContentControls/VerticalMenu.ascx");//loads menu control (vertical)
Control socialmedia = (Control)Page.LoadControl("~/ContentControls/SocialMediaBar.ascx");//loads social media links
plcBrandHead.Controls.Add(branding);
plcLeftArea.Controls.Add(menu);
plcLeftArea.Controls.Add(socialmedia);

and finally i want to access a div ("SocialMediaBar") in one of the controls i just added, and change it's css class, but 


HtmlGenericControl ctrlSocialMedia = this.Page.FindControl("SocialMediaBar") as HtmlGenericControl;

is not finding the div, so is null and 


ctrlSocialMedia.Attributes["class"] = "vertical";

throws an error.


so i am wondering how i can make sure i can find that div.





dcgate



plcBrandHead.Controls.Add(branding);
plcLeftArea.Controls.Add(menu);
plcLeftArea.Controls.Add(socialmedia);




Are remaining two not null, have you checked, as there can be two reasons;


When you add controls dynamically, you must re-add them when the page posts back (In Page_Init is a good place). See How to persist a dynamic control


The other is that Page.FindControl() only goes one level down, you need to recursively search down the list. See Better way to find control in ASP.NET


URL 


You can also try to give ID to your dynamic controls



all the controls are added and display fine, including the one containing the div i am trying to access... for some reason though i can't actually find the div.


thanks i will check out the links.


--------------------------


Edit - so the key is, as you point out that "Page.FindControl() only goes one level down" - the div I am trying to find is 2 levels down, being inside the control "socialmedia", not the Page. so switching the find control to


            HtmlGenericControl ctrlSocialMedia = socialmedia.FindControl("SocialMediaBar") as HtmlGenericControl;            

means that now ctrlSocialMedia isn't returning Null. So 


ctrlSocialMedia.Attributes["class"] = "vertical";

can work.


thanks!


[RESOLVED] Modal is closing used Update Panel.


I have a update panel which including 3 dropdownlist. and those dropdown items can change depend on first dropdown. and also I have modal popup independent these dropdownlists.

but when I click the button and open modal the page does postback and modal was closing quickly how can I get rid of this issues. and below this my code.


       







xxx


























xxxx





TL




xxx




















 





T-Law


but when I click the button and open modal the page does postback and modal was closing quickly how can I get rid of this issues.


You can stop the postback from button by adding return false like given below


  <%--Prevent the page postback using return false--%>



I am grateful to you A2H Master :)



Glad to be of help :)