Why showing error in Context.Response.Write() - c#

I'm new in ASP.Net development, and facing problem in sending data from webService to webform. I'm using JSON method,but in following line of code I'm having issue. The compiler shows this error message.
"Error 3 Invalid token '(' in class, struct, or interface member
declaration
Can someone tell me what is the problem?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting;
/// <summary>
/// Summary description for GetStudent
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class GetStudent : System.Web.Services.WebService {
[WebMethod]
public GetStudent () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public void GetStudent () {
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename='C:\\Users\\Abdul Basit Mehmood\\Documents\\Visual Studio 2012\\WebSites\\WebSite1\\App_Data\\Database.mdf';Integrated Security= True");
List<StudentsList> stu = new List<StudentsList>();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From Student";
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
StudentsList student = new StudentsList();
student.Id = Convert.ToInt32(DR["Id"]);
student.name = DR["name"].ToString();
student.fname = DR["fname"].ToString();
student.email = DR["email"].ToString();
student.contact = DR["contact"].ToString();
student.Pname = DR["Pname"].ToString();
student.Cname = DR["Cname"].ToString();
StudentsList.Add(student);
}
JavaScriptSerializer js = new JavaScriptSerializer(StudentsList());
Context.Response.Write(js.Serializ(StudentsList));
}
}

Here is how you need to fix your GetStudent method -
[WebMethod]
public void GetStudent () {
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename='C:\\Users\\Abdul Basit Mehmood\\Documents\\Visual Studio 2012\\WebSites\\WebSite1\\App_Data\\Database.mdf';Integrated Security= True");
List<StudentsList> stu = new List<StudentsList>();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From Student";
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
StudentsList student = new StudentsList();
student.Id = Convert.ToInt32(DR["Id"]);
student.name = DR["name"].ToString();
student.fname = DR["fname"].ToString();
student.email = DR["email"].ToString();
student.contact = DR["contact"].ToString();
student.Pname = DR["Pname"].ToString();
student.Cname = DR["Cname"].ToString();
stu.Add(student); //Changed line: Changed variable name to stu which is the list variable declared earlier.
}
JavaScriptSerializer js = new JavaScriptSerializer(); //changed line : Removed the invalid parameter to the constructor of JavaScriptSerializer class
Context.Response.Write(js.Serializ(stu)); //changed line : Used the correct stu list variable declared at the starting of the method.
}
Note: Please follow extreme caution while naming your class. Your StudentList entity isn't a list but an individual student entity with various properties like Id,name,fname etc. Please consider renaming it to Student.
In order to validate that you aren't getting any invalid characters from your database first try running if below code works fine or not?
class Program
{
static void Main(string[] args)
{
List<StudentsList> stu = new List<StudentsList>();
StudentsList student = new StudentsList();
student.name = "Abdul Basit Mehmood";
student.fname = "Abdul";
stu.Add(student);
JavaScriptSerializer js = new JavaScriptSerializer();
var serializedValue = js.Serialize(stu);
}
}
class StudentsList
{
public string name;
public string fname;
}
serializedValue variable should show you a valid JSON string in quick watch window as shown below:

Related

add list the Search a substring in C#

I'm create the application, but i have one question.
The client write the name of user in textbox, example 3 letters and search in database(access) and add the database.
Example: User: Rui.
and search in database all nameuser "Rui".
//libraries
using Microsoft.VisualStudio.OLE.Interop;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
private void textBox1_TextChanged(object sender, EventArgs e)
{
OleDbConnection conexao = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= {0}\Teste.accdb", Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));
List<string> Users = new List<string>();
OleDbCommand STK = new OleDbCommand($"SELECT NÂșCliente, NomeUser, CodigoPostal, NIF", conexao);
STK.CommandText = $" SELECT* FROM MyTable WHERE Str(Lista_Pokemon) like '*{textBox1.Text}*'";
User.Clear();
//this code is invention, probably is wrong
for(int d=0; d<Stk.Count()-1; d++)
User.Add(...);
}
If you can help my thanks. This project is c#, net framework and the database is Access 2010. At the moment I dont create the class, but if you need tell my, i need created.
You need create a DbReader and move to next row until end:
OleDbCommand STK = new OleDbCommand($"SELECT NÂșCliente, NomeUser, CodigoPostal, NIF", conexao);
STK.CommandText = $" SELECT * FROM MyTable WHERE Str(Lista_Pokemon) like '%{textBox1.Text}%'";
Users.Clear();
var reader = STK.ExecuteReader();
while (reader.Read())
Users.Add(reader["Lista_Pokemon"].ToString());
Threading user input into the query text is considered a dangerous practice in terms of security and also not logically unsafe.
It is better to act "according to the book" with parameters:
OleDbCommand STK = new OleDbCommand();
STK.Connection = conexao;
STK.CommandText = "SELECT * FROM tblCliente WHERE User like #userParameter";
STK.Parameters.AddWithValue("#userParameter", $"%{textBox1.Text}%")
Users.Clear();
var reader = STK.ExecuteReader();
while (reader.Read())
Users.Add(reader["User"].ToString());
Look at the following code.
The using operator is used here to release resources - this is important!
var dataSource = Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
"Teste.accdb");
var builder = new OleDbConnectionStringBuilder();
builder.Provider = "Microsoft.ACE.OLEDB.12.0";
builder.DataSource = dataSource;
var connectionString = builder.ToString();
var sql = "SELECT ..."; // place your query here
using (var connection = new OleDbConnection(connectionString))
{
connection.Open();
using (var command = new OleDbCommand(sql, connection))
using (var reader = command.ExecuteReader())
{
var users = new List<User>();
while (reader.Read())
{
var user = new User();
user.ClientNumber = (int)reader["NÂșCliente"];
user.UserName = (string)reader["NomeUser"];
user.CodigoPostal = (string)reader["CodigoPostal"];
user.NIF = (string)reader["NIF"];
users.Add(user);
}
// return users; // Return data from method
}
}
This class is used for storing user data.
Change the property names and types to the ones you need.
class User
{
public int ClientNumber { get; set; }
public string UserName { get; set; }
public string CodigoPostal { get; set; }
public string NIF { get; set; }
}
And, of course, use parameters in sql queries, as #dovid showed in his example.
Thanks Alexander Petrov and dovid, givend the solution to my problem. But i "found" the solution and i send.
OleDbConnection conexao = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= {0}\Teste.accdb", Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));
OleDbCommand STK = new OleDbCommand("SELECT * FROM MyTable ORDER BY Id");
conexao.Open();
comando.Connection = STK;
var reader = comando.ExecuteReader();
var users = new List<User>();
while (reader.Read())
{
var user = new User();
user.ClientNumber = (reader["ClientNumber "]);
user.UserName= reader["UserName"];
user.CodigoPostal= reader["CodigoPostal"];
user.NIF= reader["NIF"];
users.Add(user);
}
class User
{
public string ClientNumber { get; set; }
public string UserName { get; set; }
public string CodigoPostal { get; set; }
public string NIF { get; set; }
}

The UserId, Password or Account is invalid Teradata .Net Connection

The below code throws an error
The UserId, Password or Account is invalid.
on the code line adapter.Fill(ds);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Teradata.Client.Provider;
using System.Data;
using System.Diagnostics;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TdConnectionStringBuilder connectionStringBuilder = new TdConnectionStringBuilder();
connectionStringBuilder.DataSource = "URL";
connectionStringBuilder.Database = "DB";
connectionStringBuilder.UserId = "USERNAME";
connectionStringBuilder.Password = "PASSWORD";
connectionStringBuilder.AuthenticationMechanism = "LDAP";
TdConnection cn = new TdConnection();
cn.ConnectionString = connectionStringBuilder.ConnectionString;
cn.Open();
TdCommand cmd = new TdCommand("EXEC MACRO", cn);
TdDataReader reader = cmd.ExecuteReader();
TdDataAdapter adapter = new TdDataAdapter(cmd.CommandText, cn.ConnectionString);
DataSet ds = new DataSet();
adapter.Fill(ds);
// myLabel.Text= ds.Tables[0].Rows[0]["event_id"].ToString();
cmd.Dispose();
cn.Close();
}
}
However, the below code works perfectly fine and returns value as expected.
TdConnectionStringBuilder connectionStringBuilder = new TdConnectionStringBuilder();
connectionStringBuilder.DataSource = "URL";
connectionStringBuilder.Database = "DB";
connectionStringBuilder.UserId = "USERNAME";
connectionStringBuilder.Password = "PASSWORD";
connectionStringBuilder.AuthenticationMechanism = "LDAP";
TdConnection cn = new TdConnection();
cn.ConnectionString = connectionStringBuilder.ConnectionString;
cn.Open();
TdCommand cmd = new TdCommand("Show table DB.TABLE1", cn);
String customers = (String)cmd.ExecuteScalar();
MeanTime.Text = customers;
cmd.Dispose();
cn.Close();
The user ID, Password, Datasource etc are all same yet it fails on 1st code but runs properly on 2nd.
When calling procs and macros you can use the TDCommand.ExecuteNonQuery.
UPDATE: Upon further reading here it looks like you can include the CALL when using the Stored Procedure commandtype. The proper Commandtype for a Macro execution is System.Data.CommandType.Text and you probably need the EXEC
For reference, with parameter binding and a procedure, here's a working example below. Some small tweaks would need to be made (as mentioned above) for a macro execution.
//create a new td connection
TdConnection cn = new TdConnection();
//Build the connection string
TdConnectionStringBuilder connectionStringBuilder = new TdConnectionStringBuilder();
connectionStringBuilder.DataSource = "serveraddress";
connectionStringBuilder.Database = "defaultdatabase";
connectionStringBuilder.UserId = "username";
connectionStringBuilder.Password = "password";
connectionStringBuilder.AuthenticationMechanism = "LDAP";
connectionStringBuilder.CommandTimeout = 120;
//Open the connection
cn.ConnectionString = connectionStringBuilder.ConnectionString;
cn.Open();
// Initialize TdCommand from the tdconnection
TdCommand cmd = cn.CreateCommand();
//CommandText is set to Stored Procedure name, in this case,
//.NET Data Provider will generate the CALL statement.
cmd.CommandText = "yourdatabasename.yourprocname";
cmd.CommandType = CommandType.StoredProcedure;
// Create Input Parameter required by this procedure
TdParameter InParm1 = cmd.CreateParameter();
InParm1.Direction = ParameterDirection.Input;
InParm1.DbType = DbType.String;
InParm1.Size = 20;
InParm1.Value = "yourparamvalue";
//and bind it
cmd.Parameters.Add(InParm1);
//------------OPTION 1 CATCHING AN OUTPUT PARAMETER---------------------
//If you are catching an output parameter from a proc then create here:
// Create Output Parameter.
TdParameter OutParm = cmd.CreateParameter();
OutParm.Direction = ParameterDirection.Output;
OutParm.ParameterName = "myOutputParam";
OutParm.DbType = DbType.String;
OutParm.Size = 200;
cmd.Parameters.Add(OutParm);
// Run it up
cmd.ExecuteReader()
//if this is returning a single value you can grab it now:
myOutput = OutParm.Value.ToString();
//------------OPTION 2 CATCHING A RECORDSET-----------------------------
//list based on class set in seperate model
List<myClass> l_myclass = new List<myClass>();
//run it up and catch into a TDDataRead
using (TdDataReader r = cmd.ExecuteReader())
{
if (r.HasRows)
{
//Loop the result set and catch the values in the list
while (r.Read())
{
//"myclass" class defined in a seperate model
//Obviously you could do whatever you want here, but
//creating a list on a class where the column1-column4 is defined makes short work of this.
//Then you can dump the whole l_myclass as json back to the client if you want.
myClass i = new myClass();
i.column1 = (!r.IsDBNull(0)) ? r.GetString(0) : string.Empty;
i.column2 = (!r.IsDBNull(1)) ? r.GetString(1) : string.Empty;
i.column3 = (!r.IsDBNull(2)) ? r.GetString(2) : string.Empty;
i.column4 = (!r.IsDBNull(3)) ? r.GetString(3) : string.Empty;
l_myClass.Add(i);
}
}
}
//Dump the list out as json (for example)
return Json(l_myClass, System.Web.Mvc.JsonRequestBehavior.AllowGet);
I've only, personally, used this on procedures, but the documentation I've read suggests that this is the correct route for macros as well.

Calling a Method to a List

So i need to pass a list from this method:
[WebMethod]
public List<SLA_ClassLibrary.SLA_Class.ReadAtm> ReadAtm()
{
var AtmReadList = new List<SLA_ClassLibrary.SLA_Class.ReadAtm>();
using (SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SLAdb"].ConnectionString))
{
using (Conn)
{
Conn.Open();
string SQLReadAtm = "Select * from ATM;";
SqlCommand ReadAtmCmd = new SqlCommand(SQLReadAtm, Conn);
SqlDataReader reader = ReadAtmCmd.ExecuteReader();
while (reader.Read())
{
AtmReadList.Add(new SLA_ClassLibrary.SLA_Class.ReadAtm
{
idatm = reader.GetInt32(reader.GetOrdinal("IDATM")),
District_Region = reader.GetString(reader.GetOrdinal("District_Region")),
Local = reader.GetString(reader.GetOrdinal("Local")),
IsUp = reader.GetBoolean(reader.GetOrdinal("IsUp"))
});
}
}
return AtmReadList;
}
}
to a website table in MVC, but i'm having problems on how to go about doing this.
I can't pass the "return AtmReadList" to a List<> so i have no idea on how to do this.
Any way to do this?

can't access my new class in c# (webb-app)

Hello i am learning to program but currently i am stuck.
When i add this class directly in to the file that should be using the class, it works.
When i place this class en in a seperate .cs file, i can't seem to use it.
This is my DAL class for accessing my database (very basic)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
/// <summary>
/// Summary description for DAL
/// </summary>
public class DAL
{
// We valideren de gegevens die de gebruiker ingeeft met de gegevens in de database.
public static bool CheckUser(string username, string password)
{
DataTable result = null;
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RTIdb"].ConnectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Wachtwoord FROM Gebruikers Where GebruikersNaam = #uname";
cmd.Parameters.Add(new SqlParameter("#uname", username));
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
result = new DataTable();
da.Fill(result);
}
if (password.Trim() == result.Rows[0]["Wachtwoord"].ToString().Trim())
{
// Als we hier geraken zijn de ingevoerde gebruikersnaam en wachtwoord correct
return true;
}
}
}
}
catch (Exception ex)
{
// problem handling
}
// gebruikersnaam niet gevonden
return false;
}
public static string GetWeergaveNaam(string username)
{
DataTable result = null;
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RTIdb"].ConnectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT WeergaveNaam FROM Gebruikers WHERE GebruikersNaam = #uname";
cmd.Parameters.Add(new SqlParameter("#uname", username));
using (SqlDataAdapter da = new SqlDataAdapter())
{
result = new DataTable();
da.Fill(result);
}
if (result.Rows.Count == 1)
{
return result.Rows[0]["WeergaveNaam"].ToString().Trim();
}
}
}
}
catch (Exception)
{
// TODO opvangen exception
}
return "SQL ERROR";
}
// Nu moeten we de rol van de gebruiker nog opzoeken
public static string GetUserRoles(string username)
{
DataTable result = null;
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RTIdb"].ConnectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Roles FROM Gebruikers WHERE GebruikersNaam = #uname";
cmd.Parameters.Add(new SqlParameter("#uname", username));
using (SqlDataAdapter da = new SqlDataAdapter())
{
result = new DataTable();
da.Fill(result);
}
if (result.Rows.Count == 1)
{
return result.Rows[0]["Roles"].ToString().Trim();
}
}
}
}
catch (Exception ex)
{
// exception handling
}
// user id not found, dus is hij een gast
return "guest";
}
}
now when i want to access these methods in a different file like
DAL.CheckUser(username, password);
then i get an error in visual studio saying : "The name 'DAL' does not exist in the current context"
I would assume it hase something todo with namespaces, but i don't have any namespaces declared in any file. Whe i do add the "namespace" declaration, it does not find the namespace in my second file... so in other words i am stuck :-s
I hope someone can send me in the right direction...
Please check again about using namespace keyword of your project. I compiled successfully with two classes on two files in two difference folders.
File Business.cs in project folder
public class Business
{
public void TestFunc()
{
DAL.TestFunction();
}
}
File DAL.cs in DAL folder
public class DAL
{
public static void TestFunction()
{
//Do something
}
}
Your class isn't inside a namespace.
To refer to a class that isn't inside a namespace you should use:
global::DAL.CheckUser(username, password);
Be aware, it's a bad practice not declaring namespaces.
There are 2 options for namespacing in here:
1) You can declare both files in the same namespace;
2) You can declare both files in different namespaces and declare a using command in the file which needs to refer to the other namespace.
Namespaces group your classes in logical groups. Usually the location of the class in the folder structure of the project is used. Files in 1 namespace can call the protected and public members of each others without a using command. Files in different namespaces need to make an explicit using reference to the other namespace.

c# asp.net dropdown list select value

I am getting confused with my code and not sure how to implement what I want.
I have two sql tables one that has OfficeID and matching OfficeName and another one that contains user. I have a page that allows a person to edit information about the person. When the page is loaded it supposed to select from the drop down list the current OfficeName of a person whose information is being edited. Thus I have this:
This is probably extremely inefficient and confusing for my level of knowledge of C# and SQL, but none the less I am determined to learn how to do it. What I have currently is Before the creation of the drop down list I get the users Id, then select from the database his corresponding officeID, then while creating the drop down list I check for the OfficeID to correspond to the ones from the other table. If it found the match it will set it as the selected value for the drop down list.
am I on the right track? I need to figure out how to compare SESLoginID = loginID before I convert loginID before hand. Any help?
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Functions;
using HelloApp;
public partial class UserUpdate : Page
{
private Int32 loginID = 0;
protected void Page_Load(object sender, EventArgs e)
{
loginID = Convert.ToInt32(Request.QueryString["SESLoginID"]);
if (!Page.IsPostBack)
{
BindBusinessUnitDDL();
}
}
protected void BindBusinessUnitDDL()
{
SqlConnection conn;
string sql;
SqlCommand cmd;
int error;
conn = Database.DBConnect(out error);
sql = String.Format("SELECT OfficeID FROM SESLogin WHERE SESLoginID = loginID");
cmd = new SqlCommand(sql, conn);
SqlDataReader rdrr = cmd.ExecuteReader();
ListItem office = new ListItem();
office.Value = Convert.ToString(rdrr.GetInt32(0));
Database.DBClose(conn);
sql = String.Format(
"SELECT OfficeID, OfficeName FROM Office");
cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader();
DropDownList ddlBusinessUnit = (DropDownList)(this.LoginFormView.FindControl("ddlBusinessUnit"));
while (rdr.Read())
{
ListItem myItem = new ListItem();
myItem.Value = Convert.ToString(rdr.GetInt32(0));
myItem.Text = rdr.GetString(1);
ddlBusinessUnit.Items.Add(myItem);
if(office.Value == myItem.Value){
ddlBusinessUnit.SelectedValue = myItem.Text;
}
}
Database.DBClose(conn);
ddlBusinessUnit.DataBind();
PageUser myUser = new PageUser();
}
A different version of the code where there exists a procedure to return OfficeName using an LoginID. Doesnt work either gives an error:
System.Data.SqlClient.SqlException: Conversion failed when converting the nvarchar value ' SELECT
[OfficeName]
FROM sesuser.SESLogin
INNER JOIN sesuser.Office
ON sesuser.Office.OfficeID = sesuser.SESLogin.OfficeID
WHERE SESLoginID LIKE '287'' to data type int.
public partial class UserUpdate : Page
{
private Int32 loginID = 0;
private String loginIDE = "";
protected void Page_Load(object sender, EventArgs e)
{
loginIDE = Request.QueryString["SESLoginID"];
loginID = Convert.ToInt32(Request.QueryString["SESLoginID"]);
if (!Page.IsPostBack)
{
BindBusinessUnitDDL();
}
}
protected void BindBusinessUnitDDL()
{
SqlConnection connec = null;
SqlCommand cmd = null;
string sqls = "";
int errNum = 0;
connec = Database.DBConnect(out errNum);
if (errNum != 0)
throw new Exception("Database Connection Error.");
sqls = "Login_GetOffice";
cmd = new SqlCommand(sqls, connec);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userID", loginIDE);
string office = (string)cmd.ExecuteScalar();
SqlConnection conn;
string sql;
int error;
conn = Database.DBConnect(out error);
sql = String.Format(
"SELECT OfficeID, OfficeName FROM Office");
cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader();
DropDownList ddlBusinessUnit = (DropDownList)(this.LoginFormView.FindControl("ddlBusinessUnit"));
while (rdr.Read())
{
ListItem myItem = new ListItem();
myItem.Value = Convert.ToString(rdr.GetInt32(0));
myItem.Text = rdr.GetString(1);
ddlBusinessUnit.Items.Add(myItem);
if(office == myItem.Text){
myItem.Selected = true;
}
}
Database.DBClose(conn);
ddlBusinessUnit.DataBind();
PageUser myUser = new PageUser();
}
You can assign a DataSource and Bind the results you get from the query say via a DataTable.
Set the DataTextField and DataValueField
Then you can say something like ddl.Items.FindByText("requiredloginid").Selected = true after the Data is bound to the dropdown.
Why are you using
ddlBusinessUnit.DataBind();?
You are binding any data source to the dropdownlist.
Can you specify on which line you are getting error?
Thanks
Ashwani

Categories

Resources