I am creating a website. The home page has a text box and drop down box in which the user enters the movie name and language to search. When the user clicks on the Search button the search result page is displayed and the results of search should be displayed in a data grid. I created session variables to pass the text of the text box and data grid to be used in the other page. The code to fetch data from the database is in a class how do i pass the values received from the database to a method of another page? This is the code i have written, it doesn't give any errors but the data grid does not get filled with results what am I doing wrong?
//Code for search button in home page
protected void Btnsearch_Click(object sender, EventArgs e)
{
Response.Redirect("SearchResults.aspx");
Session["moviename"] = TextBox3.Text;
Session["language"] = DropDownList1.Text;
}
//Code to fetch data from database
public class movie
{
public SqlDataAdapter searchmovie(object moviename, object language)
{
connection.con.Open();
SqlDataAdapter adapter1 = new SqlDataAdapter("select
select movieName,language,director,price from movie
where moviename = '" + moviename + "' and
language = '" + language + "'",
return adapter1;
}
}
//Code in search page to fill data grid with search results
public partial class SearchResults : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
movie m = new movie();
SqlDataAdapter movieDetails = m.searchmovie(Session["moviename"],
Session["language"]);
DataSet data = new DataSet();
movieDetails.Fill(data, "movieD");
GridView1.DataSource = data.Tables["movieD"];
GridView1.DataBind();
}
}
Set the session variables before redirecting, like this:
protected void Btnsearch_Click(object sender, EventArgs e)
{
Session["moviename"] = TextBox3.Text;
Session["language"] = DropDownList1.Text;
Response.Redirect("SearchResults.aspx");
}
I would like to suggest to avoid Session as data storage.
ASP.NET has a nice feature called cross-posting: it make you able all the page control and state from a page to another.
http://msdn.microsoft.com/en-us/library/ms178139.aspx
Personally, I really love feature because you can refer to page as object, having controls exposed ad property!
Related
I have two pages. On the first one I have two drop down lists and button like this:
Code for this button is:
protected void btnIzabraniProizvodi_Click(object sender, EventArgs e)
{
Session["Id_Dobavljaca"] = ddlDobavljaci.SelectedValue;
Session["Id_Kategorija"] = ddlKategorija.SelectedValue;
Response.Redirect("IzabraniProizvodi.aspx");
}
When I click on this button the secont page opens.
This two sessions are input parameters for the SQL query. Here is the code on the second page:
protected void Page_Load(object sender, EventArgs e)
{
string idDobavljaca = Session["Id_Dobavljaca"].ToString();
string idKategorija = Session["Id_Kategorija"].ToString();
string konekcioniString = ConfigurationManager.ConnectionStrings["moja_konekcija"].ConnectionString;
using (SqlConnection sqlKonekcija = new SqlConnection(konekcioniString))
{
SqlDataAdapter sqlDA = new SqlDataAdapter("spVratiIzabraneProizvode", sqlKonekcija);
sqlDA.SelectCommand.Parameters.AddWithValue("#Id_dobavljaca", idDobavljaca);
sqlDA.SelectCommand.Parameters.AddWithValue("#Id_kategorija", idKategorija);
sqlDA.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
sqlDA.Fill(ds);
ds.Tables[0].TableName = "IzabraniProizvodi";
gridView.DataSource = ds.Tables["IzabraniProizvodi"];
gridView.DataBind();
}
}
My question is, when this dataSet is empty how can I get some message on the first page below the button: "No information for this values, try again with different values"? Any idea?
There is no way to do this normally and you have two not good ways:
You can use child and parent page. The second page will be the child of first page and data will send from child to parent by javascript. but the problem is that this does not work in chrome for security reasons.
The second way is to check automatically from first page by ajax method in periods of times.
setInterval(function(){ AJAX-CHECK }, 5000)
If you want each one of those senarios i will more explain.
I have a web application that I am developing that has an 'my profile' page. This page grabs all the users info and populates the appropriates fields.
Certain details have been blacked out for privacy reasons. This is working great. What i want to achieve is the ability for the user to edit any of these text fields, and hit the 'update information' button. I am not sure how to do this.
Here is my code behind for what I have working so far.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grabData();
}
}
protected void grabData()
{
HttpCookie cookieLogin = Request.Cookies[Constants.CK_CAUSE_MARKETER_ID];
string sql = "SELECT * " +
"FROM CauseMarketers m with(nolock)" +
"INNER JOIN CauseMarketer_Contacts t with(nolock) ON t.CauseMarketerID = m.CauseMarketerID " +
"INNER JOIN CauseMarketer_Companies q ON q.CauseMarketerID = m.CauseMarketerID " +
"WHERE m.CauseMarketerID = " + cookieLogin.Value;
DataTable Results = Utils.SQLUtils.GetDataTable("TFOUNDATION", sql);
DataRow FirstResult = Results.Rows[0];
userFirstName.Text = FirstResult["FirstName"].ToString();
userLastName.Text = FirstResult["LastName"].ToString();
userCompanyName.Text = FirstResult["CompanyName"].ToString();
userAddress.Text = FirstResult["Address1"].ToString();
userAddress2.Text = FirstResult["Address2"].ToString();
userCity.Text = FirstResult["City"].ToString();
userZip.Text = FirstResult["ZipCode"].ToString();
}
Implement update information button click event.
<asp:Button ID="UpdateId" runat="server" Text="Update Information" OnClick="UpdateId_Click" />
If above the asp.net button then button client event look something like below.
protected void UpdateId_Click(object sender, EventArgs e)
{
// write update sql.
}
During first page load anyway information will get loaded based on your code. When user clicks on button this click event gets fired and you can capture all form information and send to db for update.
i have two page ,one search.aspx and show.aspx
in search.aspx i have 2 textbox and 1 dropdownlist of location,title,experience
now when person click on search button , if person have filled location than gridview show all data of that location,if person fill both location and title than it should show data with both condition of location and title ,and if person fill all textbox and dropdownlist than it should show data with that location title and experience
now as i have gridview in another page so i am transferring all textbox and dropdown value to another page through querystring but it is not showing any data
and another what should be stored procedure for searching like this?
i have made something like
stored procedure-(it wrong but what it actually should be?)
ALTER PROCEDURE search
(
#Location nvarchar(50),
#Experience nvarchar(50),
#Title nvarchar(50)
)
AS
select * from Jobs where
Location=#Location and
Experience=#Experience and
Title=#Title
or
Location=#Location
or
Experience=#Experience
or
Title=#Title
search.aspx-
protected void imgbtnsubmit_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect("show.aspx?loc,title,exp="+textloc.text+txttitle.Text+dropdownlistexperience.SelectedItem);
}
in show.aspx page ,it takes this this value in querystring and show perticular data in grdview
show.aspx-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dal.location = Request.QueryString["loc"];
dal.title = Request.QueryString["title"];
dal.exerience = Request.QueryString["exp"];
GridView1.DataSource = bal.search(dal);
GridView1.DataBind();
}
}
bal-
public DataTable search(portalDal dal)
{
con.Open();
cmd = new SqlCommand("search", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Location", dal.location);
cmd.Parameters.AddWithValue("#Experience", dal.experience);
cmd.Parameters.AddWithValue("#Title", dal.title);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
return dt;
}
errors- Procedure or function 'search' expects parameter '#Location', which was not supplied.
Your querystring isn't formatted correctly and your textloc.text should be ".Text"
protected void imgbtnsubmit_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect(string.Format("show.aspx?loc={0}&title={1}&exp={1}", textloc.Text, txttitle.Text, dropdownlistexperience.SelectedItem));
}
Btw this is a great way to get a SQL Injection Attack.
In Search Page You did mistake..
protected void imgbtnsubmit_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect("show.aspx?loc,title,exp="+**textloc.text**+txttitle.Text+dropdownlistexperience.SelectedItem);
}
txtloc.text ...it should be txtloc.Text
I have a table tblProfile, which contains fields with Id, Name, Address. I have 2 aspx page, which are Home.aspx and Here.aspx. On my Home.aspx I have used this code to pass the Id in my Here.aspx:
<asp:HyperLink ID="link" runat="server" NavigateUrl="Here.aspx?id={0}"
Font-Names="Times New Roman" Font-Size="Medium" >Click here</asp:HyperLink>
In code behind Home.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
string bID = Request.QueryString["Id"];
if (string.IsNullOrEmpty(Id))
{
Response.Redirect("Here.aspx?", true);
}
ViewState["Id"] = Id;
link.NavigateUrl = String.Format(link.NavigateUrl, Id);
}
I don't have any problem with passing the Id to url in 2nd page. But what I want right now is, on my Here.aspx, I have 3 textboxes which supposed to be filled by the Id, Name and Address of the certain Id that passed from the Home.aspx. Tried many but had no luck at all. Any help would be appreciated. By the way, I'm using asp.net with c#.
We are having two solution for it
Solution 1 : User Previous page property in asp.net so that you no need to pass ID. i.e.
protected void Page_Load(object sender, EventArgs e)
{
// Find the name on the previous page
TextBox txt = (TextBox)Page.PreviousPage.FindControl("txtNameText");
if (txt != null)
txtName.Text = Server.HtmlEncode(txt.Text);
else
txtName.Text = "[Name Not available]";
}
Solution 2 : Get ID from query string and get Data by ID in assign on text box text property.i.e.
protected void Page_Load(object sender, EventArgs e)
{
// Get value from query string
string profileID = Request.QueryString["Id"];
// Fetch data from database by ID
DataTable dt = FetchEmployeeDataByID(ProfileID);
txtName.text = dt.rows[0]["Name"].tostring();
}
From your reply on comments, I suggest to do the following:
Load your data in Here.aspx back-end (.cs file) by the Id that you retrieve from query string
Show the loaded data into your desired textbox.
You can get the name and address by retrieving the profile data from the database using the Id from the query string as the key.
So in your Here.aspx's code behind:
protected void Page_Load(object sender, EventArgs e)
{
string profileID = Request.QueryString["Id"];
// Retrive profile in your db..
var profile = Profiles.Get(p => p.ProfileID == profileID);
// Populate the textboxes
txtId.Text = profileID;
txtName.Text = profile.Name;
txtAddress.Text = profile.Address;
}
Here is the deal. I have a Master-Detail Grid scenario. The Master GridView is loaded when the page is loaded. I am using a DataView of same DataTable which loads the Master to load the Detail GridView, by filtering what I need to show in the DetailGridView. Everything works fine when I view the first row of the MasterGridView. When I try to view the second row, I the the error "column[number] not found. I also notice that the "table" variable is nothing.
public partial class Gridview_Template : System.Web.UI.Page
{
DataTable table = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
SqlDataReader reader = DBSqlHelperFactory.ExecuteReader(
myconnection,
"crm_getcustomersummary",
new SqlParameter("#customerid", "99999")
);
table.Load(reader);
MasterGridView.DataSource = table;
MasterGridView.DataBind();
}
protected void detailGrid_DataSelect(object sender, EventArgs e)
{
string searchValue ="number=" + values.ToString();
DataView dv = new DataView(
table, searchValue, "number", DataViewRowState.OriginalRows
);
DetailGridView.DataSource = dv;
// ...
}
}
Am I to put the "table" variable in a session state so it exists across call?
If you just want to persist the table between postback, then you may want to take a look at ViewState. Session is used more for persisting information across different pages.