Variable Scope issue in C# - 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.

Related

Issue Populating the details view grid with selectedindex gridview - ASP.NET , C#

On My ASP.NET page i have a dropdown list - which contains all the table names from the DB. On selecting one table from the list, a gridview below is populated with the information found in that table.
Some of the tables have plenty of columns and making it impossible to view, So l included a details view to help me to view all the columns.
On selecting a row in the gridview, the details view is populated by the rows data. AS each table has different column names and numbers, i am facing problem that the DetailsView is not populated by anything and when l click 'Edit' or 'Delete'. It gives an error that the events were not handled.
Any pointers/help would be appreciated. As should be able ot edit the information, then update it in the gridview and in turn updating it in the table.
Here is my code for populating the DetailsView
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
dtvInformation.DataSource = GridView1.SelectedRow.ToString();
dtvInformation.DataBind();
}
Below is my code for populating the Gridview
protected void DropDownList1_SelectedIndexChanged (object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter(string.Format ("SELECT * FROM {0}", drpTable.SelectedValue), con);
DataSet ds = new DataSet ();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}

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();
}
}

What is the best way to return values from another page in code behind in asp.net?

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.

How to select multiple options in a ListBox?

I have a ListBox associated to a user. The user needs to be able to choose one or more options and save these options in the SQL database, but I can save only one option.
When I created my form I used the "enable postback option" and in my "selecction mode" I have: multiple.
Here is my code:
//IN MY FORM
if (!IsPostBack)
{
ClLinea_1 seleccion = new ClLinea_1();
DataSet ds = seleccion.sqlSelectLinea_1();
DataTable dt = ds.Tables[0];
ListBoxLinea_1.DataSource = dt;
ListBoxLinea_1.DataTextField = "descripcion";
ListBoxLinea_1.DataValueField = "id_linea_1";
ListBoxLinea_1.DataBind();
}
// IN MY BUTTON
protected void btnInsertaLinea_1_Click(object sender, EventArgs e)
{
ClLinea_1 inserta = new ClLinea_1();
inserta.SqlSeleccionLinea_1(int.Parse(ListBoxLinea_1.SelectedValue.),int.Parse
(txtUsuario.Text));
}
Well you need to make sure mulitiselect property is set to true.
Then use something like.
foreach(var item in MyListBox.SelectedItems)
{
int value;
if (int.TryParse(item.ToString(), out value)
{
// insert to db 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!

Categories