I want to display an item information in gridview from data base by using it name , and i want the gridview to be in another page
i tried this code,,but it didn't work
in the first page
protected void Page_Load(object sender, EventArgs e)
{
}
public string txt
{
get
{
// Return the actual name if it is not null.
return TextBox1.Text ?? string.Empty;
}
}
}
in the second page
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=FATIMAH;Initial Catalog=makeup;Integrated Security=True");
string find = "select * from product where(name like '%' +#name+ '%')";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#name", SqlDbType.NChar).Value = txt;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "name");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
}
You can pass parameter to another page using QueryString. onclick event of button on First page do this:-
protected void Button1_Click(object sender, EventArgs e)
{
string search_word = TextBox1.Text.ToString();
Response.Redirect("~/secondpage.aspx?srch_word=" + search_word);
}
and on second page request the querystring:-
protected void Page_Load(object sender, EventArgs e)
{
string search = Request.QueryString["srch_word"];
//execute sql query to perform search operation
}
Your query looks off to me. Try "select * from product where name like '%#name%'"
Also for your parameters you can just cmd.Parameters.AddWithValue("name", nameVariable);
Not sure why you would need to specify the type in this situation.
your problem is not the SQL query, your problem is passing parameter to another page.
for this reason you can do it in at least 4 different ways.
Send Text by query string
Pass it via Post Data
Pass it via Cookie
Send it via Session
in this case you can use query string, but you have to care about security issue.
BTW, it depends on how you redirect to 2th page.
Related
I have another question posted where my query would not return the results into my sealresult Label. So I figured to ask it in a different way because I still cannot figure this out. I have the following code, it runs perfectly when the button "Search" is clicked and returns the query result. However, I have a textBox with an Id of receiptbox and I want to enable an user to input text and that be placed into the query to gather the result into the sealresult Label. How do I accomplish this? I want user input where it says RE00007544 from a textbox labeled receiptbox.
protected void receiptbox_TextChanged(object sender, EventArgs e)
{
}
protected void sealresultquery_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void searchbutton_Click(object sender, EventArgs e)
{
sealresult.Text = "";
string connString = #"Data Source=SQL;Initial Catalog=mydatabase;User ID=admin;Password=******";
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = 'RE00007544'";
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm = new SqlCommand(query, conn);
using (conn)
{
try
{
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while(reader.Read())
{
sealresult.Text += reader[0].ToString();
}
reader.Close();
}
catch(Exception ex)
{
querystatus.Text = ex.Message;
}
}
}
If I understand, I think the simplest modification to the code you provided would be:
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = '" + receiptbox.Text + "'";
However, it's not the most secure way. You shouldn't be this trusting with user input.
Learn to use parameters which will save you from sql injections.
Change your code like below.
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = #number";
//define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "#number";
param.Value = receiptbox.Text.Trim();
//add new parameter to command object
comm.Parameters.Add(param);
this is my program
public partial class message : System.Web.UI.Page
{
string constring = ConfigurationManager.ConnectionStrings["AnonymiousSocialNetworkConnectionString"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
txtuseremil.Text = Session["emid"].ToString();
}
protected void btnsend_Click(object sender, ImageClickEventArgs e)
{
SqlConnection con = new SqlConnection(constring);
string value = txtmsg.Text;
if (value.Contains(SqlCommand cmd = new SqlCommand("select keyword from messageanalysis where keyword=#value"))// <--MY PROBLEM
{
con.Open();
lblStatus.Text = "Normal"; <-- I WANT TO DERIVE THIS VALUE FROM TABLE ACCORDING TO THE VALUE I GET FROM keyword
Frdsclass.Text = "Just Friend"; <--- I WANT TO DERIVE THIS VALUE FROM TABLE ACCORDING TO THE VALUE I GET FROM keyword
SqlCommand cmd = new SqlCommand("insert into messagetable(sendid,message,userid,emotional,friendsclassify) values (#snd,#msg,#usr,#emo,#frdcl)", con);
cmd.Parameters.AddWithValue("#snd", txtsndmail.Text);
cmd.Parameters.AddWithValue("#msg", txtmsg.Text);
cmd.Parameters.AddWithValue("#usr", txtuseremil.Text);
cmd.Parameters.AddWithValue("#emo", lblStatus.Text);
cmd.Parameters.AddWithValue("#frdcl", Frdsclass.Text);
cmd.ExecuteNonQuery();
con.Close();
}
how can i search a word or sentence in database table?? is my method correct?? plz help if u have a solution
your question is not quite clear. If you want to search a substring in a varchar field you can do it with a like
SELECT * FROM yourtable WHERE yourvarcharfield LIKE '%yoursearchstring%'
if you wanto look in different fields you can chain with ...or yourotherFild like '%yousearchstring%'
if you want to search those records that start with your searchstring the condition is
..like 'yoursearchstring%'
public string GetValue (string searchValue)
{
using(SqlConnection connection = new SqlConnection(connString));
using(SqlCommand cmd = new SqlCommand(
"select keyword from messageanalysis where value=#value")
{
cmd.AddParameter("#value",searchValue);
var result = cmd.ExecuteScalar();
return (result == null)? null : result.ToString();
}
}
....
var keyword = GetValue(value);
if (keyword != null && value.Contains(keyword)){
....
You could do something like this. I've separated your select statement into a different function. This will look for your value that you pass in and return your keyword. if it doesn't find it, the function returns null. I then set it to check and see if the keyword is null (since null is not found) and if it finds the value to execute the conditional code.
Try this...
NOTE:ExecuteScalar() will returns the first record of the resultset.
public partial class message : System.Web.UI.Page
{
string constring = ConfigurationManager.ConnectionStrings["AnonymiousSocialNetworkConnectionString"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
txtuseremil.Text = Session["emid"].ToString();
}
protected void btnsend_Click(object sender, ImageClickEventArgs e)
{
SqlConnection con = new SqlConnection(constring);
string value = txtmsg.Text;
SqlCommand cmd = new SqlCommand("select keyword from messageanalysis where keyword = #value")
cmd.Parameters.AddWithValue("#value", Keywordtextbox.text);
cmd.Connection=con;
con.Open();
if (Keywordtextbox.text.Contains(cmd.ExecuteScalar()))
{
lblStatus.Text = "Normal";
Frdsclass.Text = "Just Friend";
SqlCommand cmd = new SqlCommand("insert into messagetable(sendid,message,userid,emotional,friendsclassify) values (#snd,#msg,#usr,#emo,#frdcl)", con);
cmd.Parameters.AddWithValue("#snd", txtsndmail.Text);
cmd.Parameters.AddWithValue("#msg", txtmsg.Text);
cmd.Parameters.AddWithValue("#usr", txtuseremil.Text);
cmd.Parameters.AddWithValue("#emo", lblStatus.Text);
cmd.Parameters.AddWithValue("#frdcl", Frdsclass.Text);
cmd.ExecuteNonQuery();
con.Close();
}
if your textfield can contain more than one word you have to separate the words in the appropriate number of strings and then
select the records with a like saerch as shown in my previous answer
SELECT * FROM yourtable WHERE yourvarcharfield LIKE '%string1%' or yourvarcharfield LIKE '%string2%' or ...
as the textfield can have various numbers of words you have to build your sqlcommand with a stringbuilder.
I'm actually storing a value using session and then redirecting to other page using image button where based on the session value I'm fetching the Data from database. I'm getting an user defined exception in the line.
please help!
adap.Fill(dt1);//[SqlException (0x80131904): Incorrect syntax near '='.]
And this my coding.
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = sender as ImageButton;
string modelId = btn.CommandArgument;
Session["modelid"] = modelId;
Response.Redirect("details.aspx");
}
public partial class details : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=VISH;Initial Catalog=VISH;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlDataAdapter adap = new SqlDataAdapter("select * from details1 where Modelid=" + Session["modelid"], con);
DataTable dt1 = new DataTable();
adap.Fill(dt1);
DataList1.DataSource = dt1;
DataBind();
}
Cast the session object to a string first.
(String) Session["modelid"]
I recommend you to avoid using string concatenation for command creation - use parameters instead.
Also, you have to check whether Session["modelid"] has value or not, because parameter with null value will cause exactly the given message:
The parameterized query '(#id nvarchar(4000))select * from details1
where Modelid=#id' expects the parameter '#id', which was not supplied
So, the code will be:
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
var id = Session["modelid"];
if (id != null)
{
SqlDataAdapter adap = new SqlDataAdapter("select * from details1 where Modelid=#id" , con);
adap.SelectCommand.Parameters.AddWithValue("#id", );
DataTable dt1 = new DataTable();
adap.Fill(dt1);
DataList1.DataSource = dt1;
DataBind();
}
}
Or use the Page.IsPostBack property if it is guaranteed that Session["modelid"] will be set after the first postback.
Or just use some default value for it.
P.S.: Also, it is not a good idea to use instance level connection where you can't Dispose (Close) it in a deterministic way. It is better to make it method level variable and use it with using clause:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=VISH;Initial Catalog=VISH;Integrated Security=True"))
{
// ...
}
}
I am trying to update table in sql server but it's not working. Here is my code
SqlConnection conn;
string connString = ConfigurationManager.ConnectionStrings["Alumnidb"].ConnectionString;
string userName;
SqlCommand cmdProfile, cmdUpdate;
SqlDataReader reader;
string UserId;
protected void Page_Load(object sender, EventArgs e)
{
userName = Request.QueryString["UserName"].ToString();
RetriveProfile();
}
protected void RetriveProfile()
{
conn = new SqlConnection(connString);
cmdProfile = new SqlCommand("SELECT Name, UserId FROM UserProfile WHERE UserName=#UserName",conn);
cmdProfile.Parameters.AddWithValue("#UserName",userName);
conn.Open();
reader = cmdProfile.ExecuteReader();
while (reader.Read())
{
TextBoxName.Text = reader["Name"].ToString();
UserId = reader["UserId"].ToString();
}
conn.Close();
}
protected void buttonUpdate_Click(object sender, EventArgs e)
{
conn = new SqlConnection(connString);
cmdUpdate = new SqlCommand("UPDATE UserProfile SET Name=#Name WHERE UserId=#UserId",conn);
cmdUpdate.Parameters.AddWithValue("#UserId",UserId);
cmdUpdate.Parameters.AddWithValue("#Name",TextBoxName.Text.ToString());
conn.Open();
cmdUpdate.ExecuteScalar();
conn.Close();
}
and .aspx file
Name: <asp:TextBox ID="TextBoxName" runat="server" ></asp:TextBox>
<asp:Button ID="buttonUpdate" runat="server" Text="UpDate"
onclick="buttonUpdate_Click"/>
It shows me the previous value as before updated. . i checked in sql server and there is also no change in there
What am i doing wrong?
Your help will be appreciated. . .Thanx
The problem is that you fill all values in Page_Load even if you are in a postback. So if the user clicks on the update-button Page_Load is fired first, all values are loaded from database and you set the TextBox.Text value to the old value. So all changes are lost.
So use the IsPostBack property:
protected void Page_Load(object sender, EventArgs e)
{
userName = Request.QueryString["UserName"].ToString();
if(!IsPostBack)
RetriveProfile();
}
Since you are getting the UserID from the sql query and you need that in the update you have several options. You could persist the userid across postbacks e.g. in ViewState or Session. This can be done in RetriveProfile.
protected void RetriveProfile()
{
conn = new SqlConnection(connString);
cmdProfile = new SqlCommand("SELECT Name, UserId FROM UserProfile WHERE UserName=#UserName",conn);
cmdProfile.Parameters.AddWithValue("#UserName",userName);
conn.Open();
reader = cmdProfile.ExecuteReader();
while (reader.Read())
{
TextBoxName.Text = reader["Name"].ToString();
UserId = reader["UserId"].ToString();
}
conn.Close();
}
Change the field UserID to be a property:
private string UserId {
get { return (string)ViewState["UserID"]; }
set { ViewState["UserID"] = value;}
}
Note that all variables are disposed at the end of every page's lifecycle due to the statelessness of HTTP. Therefore you need to persist it somewhere.
Nine options for managing persistent User State in your ASP.NET Application
I have a datagrid to display some information from a SQL table, and then a simple textbox and button to allow users to add records to the database. Problem is, when the user clicks Add, the datagrid SHOULD update, but it doesn't, any ideas? The code in question is as follows:
protected void Page_Load(object sender, EventArgs e)
{
username.Text = Session["username"].ToString();
datetime.Text = DateTime.Now.ToString();
BindData();
}
protected void BindData()
{
string SQLQuery = "SELECT * From Filters";
OleDbConnection MyConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
DataSet resultsDataSet = new DataSet();
MyConn.Open();
OleDbDataAdapter DataAdapter = new OleDbDataAdapter(SQLQuery, MyConn);
DataAdapter.Fill(resultsDataSet);
DGFilters.DataSource = resultsDataSet;
DGFilters.DataBind();
if (resultsDataSet.Tables[0].Rows.Count == 0)
{
no_records.Visible = true;
DGFilters.Visible = false;
}
else
{
DGFilters.Visible = true;
no_records.Visible = false;
}
MyConn.Close();
}
protected void AddFilter_Click(object sender, EventArgs e)
{
OleDbConnection MyConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
MyConn.Open();
string SQLInsert = "INSERT INTO Filters (FilterString) VALUES ( '" + FilterToAdd.Text + "')";
OleDbCommand MyCmd = new OleDbCommand(SQLInsert, MyConn);
MyCmd.ExecuteNonQuery();
MyConn.Close();
DataBind();
}
Any ideas?
At the bottom of your AddFilter_Click method you need to call your own BindData() so the grid can be refreshed with the new record. Right now you're calling DataBind(), which is a method on the base class Control, which is being applied to your entire web form. I'm guessing this isn't doing much of anything.
Also, in your Page_Load method, you can probably change this:
BindData();
to
if (!Page.IsPostBack)
BindData();
so that you don't bind your grid twice when the user clicks on the 'add' button.