SQL Datareader failed to bind data to GridView - c#

protected void Button1_Click(object sender, EventArgs e)
{
string query = "select * from aspnet_Users where userName like '%#UserName%'";
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = TextBox1.Text;
SqlDataReader reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
connection.Close();
}
I am trying to use connected model to search a user's data in a table but the GridView is always, never fills with data.

You parameter is acting as a string in your query because of single quotes you have include around the parameter. That is the reason it is not able to identify the parameter. Try this:-
string query = "select * from aspnet_Users where userName LIKE #UserName";
Then add it as parameter like this:-
command.Parameters.Add("#MyName",SqlDBType.NVarChar,40).Value ="%" + TextBox1.Text + "%";

You can populate gridview using SqlDataAdapter, your code look like this
string query = "select * from aspnet_Users where userName like '%#UserName%'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", TextBox1.Text);
cmd.Connection = conn;
SqlDataAdapter dap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dap.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();

Related

Search in the database

This Messages form display table with these informations (ID,FROM,TO,TITLE,MESSAGE).
I am trying to search for all the messages send to a certain user . user will enter his name in the Search_textBox then it will filter the table to keep only messages to this user.
private void Search_button_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmd.CommandText = "Select * from MessagesTable where To =" + Search_textBox.Text;
cmd.Parameters.AddWithValue("#To", Search_textBox.Text);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
I get this error :
System.Data.SqlClient.SqlException: 'Invalid column name 'To'.'
What does the "search_name" parameter contains? The Message? The Column Name?
Your query is
Select * from MessagesTable where " + search_name + " = #From"
Then you specifies the "search_name" as a parameter for the #From...
So I believe your input was "Name" and your query is looked like this now:
Select * from MessagesTable where Name = 'Name';
You do not have any Name column in this specified table as you described.
this is Correct
private void Search_button_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from MessagesTable where [To]= #To";
cmd.Parameters.AddWithValue("#To", Search_textBox.Text);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
You can change it as follows. Of course, if I understand correctly, that you want to search in the messages field by the input you get from the user.
private void Search_button_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from MessagesTable where MESSAGE = #From";
cmd.Parameters.AddWithValue("#From", search_name);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
Try with To, because "To" - keyword SQL:
cmd.CommandText = cmd.CommandText = "Select * from MessagesTable where [To] =" + Search_textBox.Text;

Table and specific SQLQuery.sql to C#

I'm importing the table 'tblTable' to Datagridview in C# with:
private void button1_Click(object sender, EventArgs e)
{
con.Open();
//
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM tblTable";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sa = new SqlDataAdapter(cmd);
sa.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
I have written a specific SQLQuery, 'SQLQuery1.sql' that does some groupings from the table 'tblTable' that I'm already importing. What would be the best way to import only the SQLQuyery1.sql in to C#, without importing all the table?
Many thanks
It would probably be best to make your query into a Stored Procedure, and call instead:
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "MyStoredProc";

Why won't my simple C# website UPDATE to db using GridView?

I have the following C# to UPDATE a record, however the textbox shows, but doesn't update to the database. Likewise, I cannot ADD a record either.
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
Add:
protected void AddNewMainPost(object sender, EventArgs e)
{
string postID = ((TextBox)GridView1.FooterRow.FindControl("txtPostID")).Text;
string Name = ((TextBox)GridView1.FooterRow.FindControl("txtSelect")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into homepageSelection(postID, selectionText) " +
"values(#postID, #selectionText,);" +
"select postID,selectionText, from homepageSelection";
cmd.Parameters.Add("#postID", SqlDbType.VarChar).Value = postID;
cmd.Parameters.Add("#selectionText", SqlDbType.VarChar).Value = Name;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Update
protected void UpdateMainPost(object sender, GridViewUpdateEventArgs e)
{
string postID = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblpostID")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSelec")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update homepageSelection set selectionText=#selectionText, " +
"where postID=#postID;" +
"select postID,selectionText from homepageSelection";
cmd.Parameters.Add("#postID", SqlDbType.VarChar).Value = postID;
cmd.Parameters.Add("#selectionText", SqlDbType.VarChar).Value = Name;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
I have two fields in the database:
Table: homepageSelection Fields: postID and selectionText
As I can see from your code above, you have a syntax error in both queries, but most important thing is the fact that you don't associate your command to the connection. Thus, unless you recreate the connection inside the GetData method, your command cannot be executed.
So, to fix the syntax errors
"select postID,selectionText from homepageSelection";
^^^ comma not valid here
cmd.CommandText = #"update homepageSelection set
selectionText=#selectionText" +
^^^^ again comma not valid here
cmd.CommandText = "insert into homepageSelection(postID, selectionText) " +
"values(#postID, #selectionText);" +
^^^ no comma here
EDIT: it seems that you create the connection inside the GetData method, thus you don't need it in the two calling methods.

passing a parameter to GridView when calling data from database

so my GridView Returns all the data in my Table but i want to return data that are related to the UserName attribute in the table,mind you that i have Multiple UserName's in the table.
i tried giving my function a string username and in my page_load:
string SessionName;
protected void Page_Load(object sender, EventArgs e)
{
SessionName = Session["Username"].ToString();
DataSet ds = InsertClass.GetCart(SessionName);
}
in my class:
public static DataSet GetCart(string UserName)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [ShoppingCart] WHERE UserName = #UserName ", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#UserName", UserName));
DataSet ds = new DataSet();
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
adapter1.Fill(ds);
conn.Close();
return ds;
}
Edit:my mistake guys i didnt add the parameter to my function because i was trying alot of things before i asked the question and forgot to put it back.
You are not passing username as string parameter here in your code public static DataSet GetCart()
Here is correct one:
public static DataSet GetCart(string userName)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [ShoppingCart] WHERE UserName = #UserName ", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", userName);
DataSet ds = new DataSet();
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
adapter1.Fill(ds);
conn.Close();
return ds;
}
So in your page_load you are calling your GetCart function with parameter SessionName, but i cannot see your GetCart function is taking any parameter:
DataSet ds = InsertClass.GetCart(SessionName);
public static DataSet GetCart()
{.....}
And what is the reference of UserName, when you add the parameter to sql query:
cmd.Parameters.Add(new SqlParameter("#UserName", UserName));
Did you debug and see that you are passing the right parameter ?

How to get ID against selected value of Dropdownlist C#

How can I get the ID against the selected value of a DropDownList which is bound with DB?
Then how can I insert this ID into another table?
To get ID code
string query = "Select ID From Table-1 Where Name=" + DropDwonList.SelectedValue;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
string getId = dr[0].ToString();
DropDownList Binding Code
string query = "Select ID, Name from Table-1";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
DropDwonList.DataSource = dt;
DropDwonList.DataTextField = "Name";
DropDwonList.DataValueField = "ID";
DropDwonList.DataBind();
DropDwonList.Items.Insert(0, new ListItem("--Select Name--"));
1) string Id = DropDwonList.SelectedValue;
2) To insert into another table just use a query:
string Id = DropDwonList.SelectedValue;
using (SqlConnection sql = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand();
string query = #"INSERT INTO TABLE2(Column1)
VALUES(" + Id + ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = sql;
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
You should do it this way because you always ensure that you are closing a connection after using it.

Categories

Resources