show search data in gridview of another page when search button click - c#

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

Related

ASP.NET CSHTML Populating a Gridview

I am hitting a wall with populating a Gridview in ASP.NET CSHTML.
On Page Load, I have this code to initiate data fill.
protected void Page_Load(object sender, EventArgs e)
{
Orisoftds = new DataSet();
using (SqlConnection appCon = new SqlConnection(appdb))
{
SqlDataAdapter orisoftAdapter = new SqlDataAdapter(fillist, appCon);
orisoftAdapter.Fill(Orisoftds, "Staff_List");
}
GridView1.DataSource = Orisoftds.Tables["Staff_List"];
}
With this , the GridView1 will now have a DataSource
On my web page I have these three controls :
In this project , user will have to fill in their ID on the Text box and by clicking the submit button, the GridView will be filled in.
On the submit button, I have these code :
protected void EmpIDSubmit_Click(object sender, EventArgs e)
{
string eID = empIDTextBox.Text;
((DataTable)GridView1.DataSource).DefaultView.RowFilter = "EMPLOYEE_ID = " + eID;
}
Am I missing anything as at the moment when I enter an ID to the textbox, the page will instead just do thing or seems like it refreshed doing nothing.
Is there a difference between filling a Gridview in WinForms and HTML?
Result should contain gridview showing only the user's profile filtered based on their ID given.
You are Missing GridView1.Databind() for DataBind with Gridview,
Please use this line after:
GridView1.DataSource = Orisoftds.Tables["Staff_List"];
I believe you are missing the DataBind method. Try calling GridView1.Databind() in your EmpIDSubmit_Click event.
Answer - I am missing databind.
GridView1.DataBind();
I had a problem where even after databind , the result did not show.
Apparently the submit button has a broken PostBackUrl configuration as i was testing another method earlier.
I deleted my button and replaced with a new one , now results are showing properly.
I no longer need to use a stored procedure method such as :
using (SqlConnection appCon = new SqlConnection(appdb))
{
using (SqlCommand cmd = new SqlCommand("StoredProcedureName", appCon))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EMPLOYEE_ID", empIDTextBox.Text);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
Thank you everyone.

Assign a value to drop down list on page_load

I'm trying to assign value to a drop down list on the page_load, but it's not automatically get selected when the page loads up. But when I try to select another value from the drop down list, then the value assigned to it originally gets selected. I think it's something to do with the PostBack, My code is,
if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
{
string selectedReg = Request.QueryString["selectedReg"];
ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
}
If I use if(!IsPostBack) still no luck, Any ideas? Thanks a lot in advance
The code block you have written is working. No need to check for postback. Be careful about your querystring. It looks like these pictures for my tests.
After your comment I changed dropdown item list. It is getting data from database. And I called this method in Page_Load
protected void Page_Load(object sender, EventArgs e)
{
FillDropDown();
if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
{
string selectedReg = Request.QueryString["selectedReg"];
ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
}
}
protected void FillDropDown()
{
using (SqlConnection con= new SqlConnection("server=.;database=StackTest;integrated security=true") )
{
SqlDataAdapter adp = new SqlDataAdapter("select * from Test", con);
DataTable dt = new DataTable("Test");
adp.Fill(dt);
ddlVehicleReg.DataValueField = "Id";
ddlVehicleReg.DataTextField = "Value";
ddlVehicleReg.DataSource = dt;
ddlVehicleReg.DataBind();
}
}

How to show a specific item in dropdownlist based on specific value of a cell of a table-row in asp.net gridview control?

i am new to asp.net. I am building an admin page and i want to display employee's data in GridView by fetching it from database table. Table has 3 columns (id, name, isManager). There are three possible values for "isManager" column. These values are "yes", "no" and "null". The admin has right to decide for an employee to make him a manager by selecting "yes" or "no" from DropDownList.
This admin page has a GridView control that contains two BoundFileds (i.e. id & name) and one template field (i.e. DropDownList). I am having difficulty in displaying "isManager" column values in DropDownList. I want DropDownList to display selected value/text as "yes" if database table-row has "yes" in "isManager" column, "no" if there is "no" in table-row and display an item "Select Choice" if table-row contains a null value.
My code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select * from tblUsersTable";
DataSet ds = DataBaseConnectivity.GetData(query);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
// RowDataBound() method
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlManager = (e.Row.FindControl("ddlManager") as DropDownList);
DataSet ds = DataBaseConnectivity.GetData
("select distinct [isManager] from tblUsersTable");
ddlManager.DataSource = ds;
ddlManager.DataTextField = "isManager";
ddlManager.DataValueField = "isManager";
ddlManager.DataBind();
ddlManager.Items.Insert(0, new ListItem("Please select","-1"));
/* After these lines of code i am not finding the right way to implement my logic
*/
Help me to figure it out.
You have to use the DataItem of the GridViewRow to access the underyling record. Then you can select the corect item via DropDownList.SelectedValue:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlManager = (e.Row.FindControl("ddlManager") as DropDownList);
DataSet ds = DataBaseConnectivity.GetData
("select distinct [isManager] from tblUsersTable");
ddlManager.DataSource = ds;
ddlManager.DataTextField = "isManager";
ddlManager.DataValueField = "isManager";
ddlManager.DataBind();
ddlManager.Items.Insert(0, new ListItem("Please select","-1"));
DataRow row = ((DataRowView)e.Row.DataItem).Row;
bool isManager= row.Field<bool>("isManager"); // use the correct type if it's not bool
ddlManager.SelectedValue = isManager.ToString();
Apart from that, i would not use such db-helper classes like DataBaseConnectivity in ASP.NET. They are just a source for nasty errors or performance issues, all the more if you use a static connection. Further informations here.

Passing values from a class to a method of another class

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!

Variable Scope issue in C#

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.

Categories