asp.net mvc using string id on details view - asp.net

Please help me to find error on my code
public ActionResult Details(string id)
{
String connectionString = ConfigurationManager.ConnectionStrings["SAPB1"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
String sql = "Select a.[CardCode] As CCODE,a.[CardName] As Name from ocrd a where a.CardCode = " + id;
SqlCommand cmd = new SqlCommand(sql, conn);
BPModel BP = new BPModel();
using (conn)
{
conn.Open();
if (string.IsNullOrEmpty(id))
{
}
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
BP.CCODE = rdr["CCODE"].ToString();
BP.Name = rdr["Name"].ToString();
}
}
return View(BP);
}

You need to wrap your id values inside single quote ('). Try like below.
String sql = "Select a.[CardCode] As CCODE,a.[CardName] As Name from ocrd a where a.CardCode = '" + id + "'";

Related

How do i fill up textbox from database in asp.net visual studio without id?

I am trying to get details of an account in a row using the Username instead of id. I have limited knowledge on this matter so im only stuck with the code that i learned in class.
I have tried changing variables, but probably wont help and the code i have provided below, would not retrieve any data from the database...
(Username are retrieved from previous page and yes it did show up in this page)
This is the code used on previous page: (code is placed on a button)
string username = Session["Username"].ToString();
Response.Redirect("EditAccountDetail.aspx?Username="+ username);
private DataTable GetData()
{
string constr = ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
This is the code im working on right now:
String Uname = Request.QueryString["Username"];
string constr = ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname+"'"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string id = row["Id"].ToString();
string Full_name = row["Full_name"].ToString();
string Username = row["Username"].ToString();
string Password = row["Password"].ToString();
string Email = row["Email"].ToString();
string DOB = row["DOB"].ToString();
string Gender = row["Gender"].ToString();
this.HiddenField1.Value = id;
this.TextBox_Name.Text = Full_name;
this.TextBox_Username.Text = Username;
this.TextBox_Password.Text = Password;
this.TextBox_Email.Text = Email;
this.TextBox_DOB.Text = DOB;
this.RadioButtonList_Gender.Text = Gender;
}
}
}
}
}
This is the code in the button:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
try
{
string query = "UPDATE Guest SET Full_name=#Full_name, Username=#Username, Password=#Password, Email=#Email, DOB=#DOB, Gender=#Gender WHERE Id=#id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", HiddenField1.Value);
cmd.Parameters.AddWithValue("#Full_name", TextBox_Name.Text);
cmd.Parameters.AddWithValue("#Username", TextBox_Username.Text);
cmd.Parameters.AddWithValue("#Password", TextBox_Password.Text);
cmd.Parameters.AddWithValue("#Email", TextBox_Email.Text);
cmd.Parameters.AddWithValue("#DOB", TextBox_DOB.Text);
cmd.Parameters.AddWithValue("#Gender", RadioButtonList_Gender.Text);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("GuestMenu.aspx");
con.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
If you are redirecting to the "GuestMenu" page, then you have to add username in the query string so that you can retrieve this on the page.
Response.Redirect("GuestMenu.aspx?Username="+TextBox_Username.Text);
By seeing your current code, you should be getting some error. Please post the error details if any.
You can try changing the query as below and check for database result
new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname + "'")

my asp.net web service code is giving error

hello i have created the code for extracting age from table test
but instead of returning the age it is returning me the following statement
System.Data.SqlClient.SqlDataReader
here is the code
[WebMethod]
public string Getcustomername(string name)
{
SqlConnection con = new SqlConnection("Data Source=GURJOT;Initial Catalog=TEST;Integrated Security=True");
SqlCommand com = new SqlCommand();
com.Connection = con;
con.Open();
com.CommandText = "SELECT * from test WHERE Name='" + name + "'";
SqlDataReader dt = com.ExecuteReader();
dt.Read();
con.Close();
dt.Close();
return dt.ToString();
any help would be appreciated
Thanks
Instead of returning dt.ToString() you should return the value of a field:
public string GetCustomerAge(string name)
{
using (SqlConnection con = new SqlConnection("Data Source=GURJOT;Initial Catalog=TEST;Integrated Security=True"))
{
using(SqlCommand com = new SqlCommand())
{
com.Connection = con;
con.Open();
com.CommandText = "SELECT age from test WHERE Name='" + name + "'";
using (SqlDataReader dt = com.ExecuteReader())
{
if (dt.Read())
{
return System.Convert.ToString(dt.GetValue(0));
}
}
}
return "";
}
And please, use parameterized queries - http://en.wikipedia.org/wiki/SQL_injection .

Unable to do search for selected items

I am using this code to search for selected items inside a checkbox list and it doesn't work.
protected void btnSearchCode_Click(object sender, ImageClickEventArgs e)
{
string selectedValues = string.Empty;
foreach (ListItem item in cblCode.Items)
{
if (item.Selected)
selectedValues += item.Value + ",";
}
if (selectedValues != string.Empty)
selectedValues = selectedValues.Remove(selectedValues.Length - 1);
cblCode.DataSource = DataReport.SearchCode(selectedValues);
cblCode.DataBind();
}
public static DataTable SearchCode(string selectedValues)
{
string strcon = ConfigurationManager.ConnectionStrings["LocalDB"].ConnectionString;
DataTable datatable = new DataTable();
using (SqlConnection conn = new SqlConnection(strcon))
{
conn.Open();
SqlCommand command = new SqlCommand();
string strQuery = "Select Group, Name from Details where Code in (" + selectedValues + ")", conn;
command.Connection = conn;
SqlDataAdapter dataadapter = new SqlDataAdapter();
dataadapter.SelectCommand = command;
DataSet ds = new DataSet();
dataadapter.Fill(datatable);
}
return datatable;
}
Really appreciate any help on this.
You have not used strQuery at all.
Try this :
public static DataTable SearchCode(string selectedValues)
{
string strcon = ConfigurationManager.ConnectionStrings["LocalDB"].ConnectionString;
DataTable datatable = new DataTable();
using (SqlConnection conn = new SqlConnection(strcon))
{
conn.Open();
string strQuery = "Select Group, Name from Details where Code in (" + selectedValues + ")";
SqlCommand command = new SqlCommand(strQuery, conn);
SqlDataAdapter dataadapter = new SqlDataAdapter();
dataadapter.SelectCommand = command;
DataSet ds = new DataSet();
dataadapter.Fill(datatable);
}
return datatable;
}
You create the query string but you never assign it to the command variable. Therefore, when you assign it to selectCommand, there isn't anything to query from DB. You want to add this line of code to assign the query string to variable:
command = new SqlCommand(strQuery,conn);
Always Use SqlParamerter while passing parameters to the database
i think You are missing single inverted comma because Your SeletedValues is string
string strQuery = "Select Group, Name from Details
where Code in ('" + selectedValues + "')", conn;

Data list where clause

i am using a datalist to display videos but i am trying to get it working now with the where clasue ...where the name is equal to wrd.mp4 i am getting the following error,
$exception {"The multi-part identifier \"wrd.mp4\" could not be bound."} System.Exception {System.Data.SqlClient.SqlException}
private void BindGrid()
{
string strConnString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name from tblFiles where Name=wrd.mp4";
cmd.Connection = con;
con.Open();
DataList1.DataSource = cmd.ExecuteReader();
DataList1.DataBind();
con.Close();
}
}
}
}
You need to use quotes:
cmd.CommandText = "select Id, Name from tblFiles where Name='wrd.mp4'";

Can't Get value from database in ASP.net

Hi can you help me with this??
I have this code and i want to display the result of my query into my 3rd Textbox but it not displaying.
string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName = '" + TextBox2.Text + "'";
if (query != null)
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
TextBox3.Text=rdr["UserID"].ToString() ;
}
}
}
}
}
But then i just use this query without the where condition i can see the output;
string query = "SELECT UserID FROM [IBSI].[sec].[Users]";
Thanks in advance
I'd recommend using parameterized queries for this task. Also, generating sql code from user input (like text boxes/memos) is prone to sql injections (user may enter any sql code into the textbox that may damage database data), so it'd be great to validate input data.
Sample parameter usage is like this:
string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName = #1";
if (query != null)
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
SqlParameter p1 = new SqlParameter("#1", TextBox2.Text);
cmd.Parameters.Add(p1);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
TextBox3.Text=rdr["UserID"].ToString() ;
}
}
}
}
}
Step through the debugger and verify that your query is returning results.
ey Bert change in your code as follows:
string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName= '"+TextBox2.Text+ "'";
if (query != null)
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
int UserId;
UserId=Convert.ToInt32(cmd.ExecuteScalar());
TextBox3.Text=UserId.ToString() ;
}
}
}

Resources