Ado.Net Fill Grid By Logged in User - c#

I need to fill a gridview with records according to the currently logged in user. My stored procedure asks for one parameter, the ID of the user. I want that parameter to be the currently logged in user but i cant figure out how to accomplish this.
My stored Procedure to grab the records:
#cnt_ID int
AS
BEGIN
SELECT TOP (100) PERCENT dbo.vtCursusPlanning.cur_CursusID AS CursusID, dbo.vtCursusPlanning.cur_Omschrijving AS Omschrijving, CONVERT(varchar,
dbo.vtData.dat_Datum, 100) AS Datum, CONVERT(varchar, dbo.vtData.dat_Start, 100) AS DStart, CONVERT(varchar, dbo.vtData.dat_Stop, 100) AS DStop,
dbo.vtContactPersonen.cnt_Initialen AS Username
FROM dbo.vtData INNER JOIN
dbo.vtCursusPlanning ON dbo.vtData.cur_FK = dbo.vtCursusPlanning.cur_CursusID INNER JOIN
dbo.vtContactPersonen ON dbo.vtCursusPlanning.cnt_FK = dbo.vtContactPersonen.cnt_ID INNER JOIN
dbo.vtCursusCursisten ON dbo.vtData.cur_FK = dbo.vtCursusCursisten.cst_fk
WHERE (dbo.vtContactPersonen.cnt_ID = #cnt_ID) AND (NOT (dbo.vtCursusCursisten.cst_fk IS NULL)) AND (NOT (dbo.vtCursusPlanning.cur_Project IS NULL))
ORDER BY DStart
END
And my attempt to fill the gridview with my C# code.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
GridView1.DataKeyNames = new string[] { "#cnt_ID" };
string connectionString = ConfigurationManager.ConnectionStrings["KRIS-Planning"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("spOffice2010Evaluaties", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("#cnt_ID", SqlDbType.Int);
comm.Parameters["#cnt_ID"].Value = UserID;
try
{
conn.Open();
reader = comm.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
}
catch (Exception ex)
{
dbErrorLabel.Text = Convert.ToString(ex);
}
finally
{
conn.Close();
}
}
}

Try this one instead;
string UserId = HttpContext.Current.User.Identity.Name;

Related

'Failed to convert parameter value from a string to a datetime'

I am currently getting this error when trying to select a date from a drop down list, once the date is selected it should Display data in a GridView depending on the drop down list value. This is achieved using a 'Where' statement equals the value of the selected index.
I understand that it is a problem with the way the dates are being displayed in the drop down list, as opposed to the way they are saved in the database. So I have tried to swap the format from dd/mm/yyyy to yyyy/mm/dd in the drop down list, to see if this fixes the problem. But I can't seem to get it to work.
Please can someone recommend a fix to this?
Drop Down List selected index change C# :
protected void DropDownList2_SelectedIndexChanged(object sener, EventArgs e)
{
String query = "SELECT Stock_Take.Username, Item.ItemID, Item.ItemDesc, Stock_Take_Item.BarQuantity, Stock_Take_Item.StorageQuantity, Stock_Take.StockTakeIDNew FROM Item INNER JOIN Stock_Take_Item ON Item.ItemID = Stock_Take_Item.ItemID INNER JOIN Stock_Take ON Stock_Take_Item.StockTakeIDNew = Stock_Take.StockTakeIDNew where Stock_Take.Username = #USER AND Stock_Take.StockDate = #DATE";
SqlConnection con = new SqlConnection(#"Data Source=(local)\;Initial Catalog=SmallBatch;Integrated Security=True;");
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#USER", SqlDbType.VarChar).Value = DropDownList1.SelectedValue;
cmd.Parameters.Add("#DATE", SqlDbType.DateTime).Value = DropDownList2.SelectedValue;
// DateTime date = Convert.ToDateTime(DropDownList2.SelectedValue.ToString());
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
con.Close();
}
Binding the dates from the database to the drop down list C# code:
private void BindDropDownList2(String field)
{
DataTable dataTable = new DataTable();
SqlConnection con = new SqlConnection(#"Data Source=(local)\;Initial Catalog=SmallBatch;Integrated Security=True;");
try
{
con.Open();
String Query = "Select StockDate, StockTakeIDNEW from Stock_Take WHERE Username = #Value1";
SqlCommand sqlCmd = new SqlCommand(Query, con);
sqlCmd.Parameters.AddWithValue("#Value1", field);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dataTable);
if (dataTable.Rows.Count > 0)
{
DropDownList2.DataSource = dataTable;
DropDownList2.DataTextField = "StockDate";
DropDownList2.DataValueField = "StockTakeIDNew";
// DropDownList2.DataTextFormatString = "(yyyy/MM/dd}";
DropDownList2.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error";
msg += ex.Message;
*I also have another drop down list, that a user selects a Username from, which in turn affects what dates are shown in the DropDownList2
Here:
cmd.Parameters.Add("#DATE", SqlDbType.DateTime).Value = DropDownList2.SelectedValue;
manually parse the value first, so it is a DateTime:
var date = DateTime.Parse(DropDownList2.SelectedValue); // TODO: replace with format etc
cmd.Parameters.Add("#DATE", SqlDbType.DateTime).Value = date;

I Can't Bring Data From Database to DropDownList Selectively (City and Town Things, System.NullReferenceException Error)

I'm facing a minor problem and I'll tell you all the details below. If you help me I would be very happy.
I have 3 tables in my database as "tbl_User", "tbl_City", "tbl_Town".
My "tbl_User" table:
userid int [PK],
email nvarchar(50),
password nvarchar(50),
city int,
town int
My "tbl_City" table:
cityno int [PK],
cityname nvarchar(50)
My "tbl_Town" table:
townno int,
townname nvarchar(50),
cityno int
As you can see, "tbl_City" and "tbl_Town" tables are related to each other. This means there are towns connected to every city.
While the user is registering on the site, he must choose city and town. So I can save city and town as number in "tbl_User".
What I want to do is: When the user goes "profile.aspx", I want the city and town name to be seen in DropDownLists selectively. And when user click DropDownListCity; I want all the other cities to appear at the same time. And when user click DropDownListTown; I want showing all towns connected to the selected city.
My code bring the city selected in the "tbl_User" and when I click DropDownListCity I can see all other cities. There is no problem here. But my code doesn't bring the town selectively. I get en error: 'System.NullReferenceException'. I think it's because the city is chosen in DropDownList but program does not see the city selected.
My code is as follows:
Fonksiyon function = new Fonksiyon();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCity();
GetTown();
GetCityAndTownSelectively();
}
}
private void GetCityAndTownSelectively()
{
if (Session["userid"] != null)
{
DataRow dr = function.GetDataRow("SELECT tbl_City.cityno, tbl_City.cityname, tbl_Town.townno, tbl_Town.townname FROM tbl_User LEFT JOIN tbl_City on tbl_City.cityno = tbl_User.city LEFT JOIN tbl_Town on tbl_Town.townno = tbl_User.town WHERE userid=" + Session["userid"].ToString());
if (dr == null)
{
Response.Redirect("default.aspx");
}
else
{
DropDownListCity.ClearSelection();
DropDownListCity.Items.FindByValue(dr[0].ToString()).Selected = true;
DropDownListTown.ClearSelection();
DropDownListTown.Items.FindByValue(dr[2].ToString()).Selected = true;
}
}
else
{
Response.Redirect("default.aspx");
}
}
private void GetCity()
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["aytasarimConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT * FROM tbl_City", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
DropDownListCity.DataSource = reader;
DropDownListCity.DataValueField = "cityno";
DropDownListCity.DataTextField = "cityname";
DropDownListCity.DataBind();
reader.Close();
}
catch
{
string message = "<script>alert('Error!');</script>";
Response.Write(message);
}
}
private void GetTown()
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["aytasarimConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT * FROM tbl_Town WHERE cityno='" + DropDownListCity.SelectedValue + "'", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
DropDownListTown.DataSource = reader;
DropDownListTown.DataValueField = "townno";
DropDownListTown.DataTextField = "townname";
DropDownListTown.DataBind();
reader.Close();
}
catch
{
string message = "<script>alert('Error!');</script>";
Response.Write(mesaj);
}
}
protected void DropDownListCity_SelectedIndexChanged(object sender, EventArgs e)
{
GetTown();
}
Program gives the error in the following line: DrpDwnLstTown.Items.FindByValue(dr[2].ToString()).Selected = true; And I think i guess i found the cause of the error: When I changed my GetTown methods SQL query like this: SELECT * FROM tbl_Town my code brings town selectively but when I click DropDownListTown I see all towns. The problem is I have to only see the town connected to the city.
This is the full code you need.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCity();
if (DropDownListCity.Items != null)
{
GetTown(Convert.ToInt32(DropDownListCity.SelectedValue.ToString()));
}
}
}
private void GetCity()
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["aytasarimConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT * FROM tbl_City order by cityName", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
DropDownListCity.DataSource = reader;
DropDownListCity.DataValueField = "cityno";
DropDownListCity.DataTextField = "cityname";
DropDownListCity.DataBind();
reader.Close();
}
catch
{
string message = "<script>alert('Error!');</script>";
Response.Write(message);
}
}
private void GetTown(Int32 selectedCityNo)
{
if (selectedCityNo == 0)
{
DropDownListTown.Visible = false;
}
else
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["aytasarimConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT * FROM tbl_Town WHERE cityno='" + selectedCityNo.ToString() + "' order by townname", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
DropDownListTown.DataSource = reader;
DropDownListTown.DataValueField = "townno";
DropDownListTown.DataTextField = "townname";
DropDownListTown.DataBind();
reader.Close();
}
catch
{
string message = "<script>alert('Error!');</script>";
Response.Write(message);
}
}
}
protected void DropDownListCity_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlCity = (DropDownList)sender;
string selectedID = ddlCity.ID;
DropDownList ddlSelectedCity = (DropDownList)FindControl(selectedID);
GetTown(Convert.ToInt32(ddlSelectedCity.SelectedValue.ToString()));
}

Running sql SubQueries in asp.net c#

hello everyone i am working on mycollege project and trying to make a user login application in asp.dot net.
I have two tables in my database one is customer full detail and other is customer login detail
What I want to do to count the row in first query and if login_id and password matches then it executes the other query to retrive and displays the customer first name, on the redirectedd page
below is what i have done any other type of method is also welcomed
here is my code
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
SqlConnection connection = new SqlConnection(conn);
connection.Open();
cmd = new SqlCommand("select COUNT(*) from customer_login where login_id = #a and pass_login=#b",connection);
cmd.Parameters.AddWithValue("#a", Login1.UserName);
cmd.Parameters.AddWithValue("#b", Login1.Password);
string user_name;
int i = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (i == 1)
{
e.Authenticated = true;
cmd = new SqlCommand("select f_name from customer where id = (select cust_id from customer_login where login_id = #a)", connection);//This query successfully runs in mssms but it gives error in aspx
// cmd.Parameters.AddWithValue("#c",new SqlCommand ("select cust_id from customer_login where login_id = #a"));
//cmd.Parameters.AddWithValue("#a", Login1.UserName);
sdr = cmd.ExecuteReader();
sdr.Read();
user_name = sdr["f_name"].ToString();
sdr.Close();
if (Session["productID"] != null)
{
Session["user"] = user_name.ToString();
Response.Redirect("~/Detail/cart.aspx");
}
else
{
Response.Redirect("Default.aspx");
}
}
else
{
e.Authenticated = false;
}
}
the problem is it gives following error "Incorrect syntax near the keyword 'select'.
Must declare the scalar variable "#a". "
thanku
because you have not assigned value to #a
cmd = new SqlCommand("select f_name from customer where id = (select cust_id from customer_login where login_id = #a)", connection);
cmd.Parameters.AddWithValue("#a",Value);
please
//cmd.Parameters.AddWithValue("#a", Login1.UserName);
uncomments this line to
cmd.Parameters.AddWithValue("#a", Login1.UserName);
then check again

Trying to get database entries limited to current UserName

I have the database updating with the UserName of the person who uploaded a file and am trying to retrieve only the files the current user uploaded, to display in the gridview.
The page displays the current user name and when that person uploads a file everything is fine. Though when that user hits the search button, all records show up and I get the error:
Error:Invalid column name 'test'
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlDataReader reader;
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM UserUpload WHERE UserName = #un";
command.Parameters.Add(new SqlParameter("#un", UN));
command.Connection = conn;
conn.Open();
reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}
Change this line
string UserSearch = "SELECT * FROM UserUpload WHERE UserName =" + UN;
to
string UserSearch = string.Format("SELECT * FROM UserUpload WHERE UserName ='{0}'",UN);
you want to match to username as string strings are being wrapped in '' in SQL
If you would be matching by number it would work fine as numbers do not have this requirement.
UPDATE to UPDATE:
Change to something like this (untested)
SqlCommand com = new SqlCommand(UserSearch, conn);
{ DataSet ds = com.ExecuteReader();
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
conn.Close();
}
You would benefit from reading this
Use Parameters instead of assinging the Value to the query string
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString(); ;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string UserSearch = "SELECT * FROM UserUpload WHERE UserName = #un";
SqlCommand com = new SqlCommand(UserSearch, conn);
com.Parameters.Add(new SqlParameter("#un", UN));
com.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}

Error while gathering tablenames from Database c# and asp.net

Database Name is ONLINEEXAM
I have several tables in the db and I want to list some table names starts with letters "set % " in Dropdownlist in asp.net.
I use the following code and I'm getting the error : invalid object name ONLINEEXAM.dbo.sysobjects
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
paperset();
}
}
private void paperset()
{
try
{
string conn = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlCommand cmd = new SqlCommand(
"select * from ONLINEEXAM.dbo.sysobjects where name like 'Set%'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
ListItem item = new ListItem();
item.Value = dr[0].ToString();
papersetlist.Items.Add(item);
}
dr.Close();
con.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally { }
}
May be you are running query against a different database, run you query in sql server to check it.
also try this
SqlCommand cmd = new SqlCommand("select * from sys.objects where name like 'Set%'", con);
or use this to get all the tables
select * from sys.tables where name like 'Set%'
Take a look to verify the user ID has access to the sysobjects table.
Assuming you are running SQL2005 or later, you can also look at the INFORMATION_SCHEMA schema and review the TABLES view:
Select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE
from [database.]INFORMATION_SCHEMA.TABLES

Categories

Resources