Unable to do search for selected items - asp.net

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;

Related

How to insert boundfield values and template field value in gridview to database

in the gridview control there are bound field and template field by clicking save button the gridview values should be saved in another table.
enter image description here
the gridview control
code tried protected void Button2_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
String S_ID = row.Cells[0].Text;
String Sub_Name = row.Cells[1].Text;
String marks = (row.Cells[2].Text);
String Semester = DropDownList2.SelectedItem.Text;
String query = "insert into Marks(S_ID,Sub_Name,Semester,Marks) values(" + S_ID + ",'" + Sub_Name + "','" + Semester + "','" + marks + "')";
String mycon = "Data Source=DESKTOP-HBMQHKE\\MSSQLSERVER01;Initial Catalog=College;Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
error : System.Data.SqlClient.SqlException: 'Incorrect syntax near 'mcl141'.'
Try to use parameters:
String query = "insert into Marks(S_ID,Sub_Name,Semester,Marks) values(#S_ID, #Sub_Name, #Semester, #marks)";
String mycon = "Data Source=DESKTOP-HBMQHKE\\MSSQLSERVER01;Initial Catalog=College;Integrated Security=True";
using (SqlConnection con = new SqlConnection(mycon))
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
cmd.Parameters.AddWithValue("#S_ID", S_ID);
cmd.Parameters.AddWithValue("#Sub_Name", Sub_Name);
cmd.Parameters.AddWithValue("#Semester", Semester);
cmd.Parameters.AddWithValue("#marks", marks);
cmd.ExecuteNonQuery();
}

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 + "'")

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'";

Detailsview in ASP.NET

I am trying to hit sql server with objectdatasource and return a datatable to fill my details view control. the selected ID value is returned by a gridview control. It seems like the datatable is not filled by adapter, and i couldn't figure out why. The ID in sql is set as a primary key (Int, 4, not null). The debugger says the Detail datatable is null. Any help is much appreciated.
public DataTable GetDetail(string ID)
{
if (ID == "")
{
return null;
}
else
{
DataTable Detail = null;
using (SqlConnection conn = new SqlConnection(connection))
{
string comm = #"select * from dbo.Products where ID = #ID";
conn.Open();
SqlDataAdapter adapter=null;
using (SqlCommand cmd = new SqlCommand(comm, conn))
{
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = Convert.ToInt32(ID);
adapter = new SqlDataAdapter(cmd);
adapter.Fill(Detail);
return Detail;
}
}
}
I think you missed the commandType
cmd.CommandType = CommandType.Text;
Try this
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connection))
{
string myquery="select * from dbo.Products where ID = #ID";
SqlCommand cmd = new SqlCommand(myquery, con);
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
cmd.Parameters.Add("#ID", SqlDbType.NVarChar, 15).Value = ID;
dap.Fill(ds);
return ds.Tables[0];
}
Thanks for ALL.
The problem is I didnt initialize my datatable to a new instance.
DataTable Detail = null; ===> DataTable Detail = new Datatable();
and also the convert should be done in sql not in codes.
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = ID;
string comm = #"select * from dbo.Products where ID = convert(int,#ID)";

updating not work in updating grid view event

i test my query in sql server and it's working 100%
but in my page not work !!
this my query
UPDATE Employee SET
Name='jojo',
Age=19,
GenderID=2,
CountryID=5,
Mobile=0917021092
WHERE EmployeeID=10
this my code
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string s = GridView1.DataKeys[e.RowIndex].Value.ToString();
Label id = (Label)GridView1.Rows[e.RowIndex].FindControl("lblEditID");
Label EmployeeID = (Label)GridView1.Rows[e.RowIndex].FindControl("lblEmployeeID");
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditName");
TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditAge");
DropDownList gender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropGender");
DropDownList country = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropCountry");
TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditMobile");
string stringconnectiong = ConfigurationManager.ConnectionStrings["Employee_TestConnectionString"].ConnectionString;
string sql = "update Employee set Name=#Name, Age=#Age,GenderID=#GenderID , CountryID=#CountryID , Mobile=#Mobile where EmployeeID=#EmployeeID AND ID=#ID";
SqlConnection con = new SqlConnection(stringconnectiong);
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID.Text);
cmd.Parameters.AddWithValue("#ID", id.Text);
cmd.Parameters.AddWithValue("#Name", name.Text);
cmd.Parameters.AddWithValue("#Age", age.Text);
cmd.Parameters.AddWithValue("#GenderID", gender.SelectedValue);
cmd.Parameters.AddWithValue("#CountryID", country.SelectedValue);
cmd.Parameters.AddWithValue("#Mobile", mobile.Text);
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
cmd.ExecuteNonQuery();
SqlDataAdapter dr = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dr.Fill(ds);
GridView1.DataSource = ds;
GridView1.EditIndex = -1;
BindGridview();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Error Updating ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
con.Close();
con.Dispose();
BindGridview();
}
}
Since your datasource is a dataset, you need to specify which data table within the dataset you are using via the DataMember propery. Or just use a data table as your datasource.
Replace the dataset lines with the following:
DataTable dt = new DataTable();
dr.Fill(dt);
GridView1.DataSource = dt;
In addition, use the GridView1_RowUpdated event. The GridView1_RowUpdating event is fired before the table is updated, therefore your parameter values have not been updated yet.

Resources