access dataset filled in page_load - c#

I have a Dataset that I fill with two sql tables in the Page_Load event. I fill my DropDownList ddlAirport00 with the values ​​of the first table. But I can not access the filled dataset from the ddlAirport00_SelectedIndexChanged(). It's like the dataset is empty or a Scope of variables trouble.
Someone can help me?
public partial class _Default : System.Web.UI.Page
{
public DataSet ds = new DataSet();
}
my Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String CS = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString1"].ConnectionString;
using (SqlConnection scon = new SqlConnection(CS))
{
//this.ds = new DataSet();
sda = new SqlDataAdapter("Select * from Aeropuerto", scon);
sda.Fill(ds, "Aeropuerto");
sda = new SqlDataAdapter("Select * from ALocalidad", scon);
sda.Fill(ds, "Localidad");
sda = new SqlDataAdapter("Select * from Tramo", scon);
sda.Fill(ds, "Tramo");
}
}
And My DDL SelectedIndexChanged() ** I Use Ajax to change the testeeric.Text
protected void ddlAirport00_SelectedIndexChanged(object sender, EventArgs e)
{
if (ds.Tables.Contains("Tramo"))
{
testeeric.Text = DateTime.Now.ToString();
}
else
{
testeeric.Text = "Brasil";
}
}

Since the data retrieving logic is located inside if (!IsPostBack), it is called only at initial page load.
So, you will need to retrieve the data from database again inside SelectedIndexChanged event.
protected void ddlAirport00_SelectedIndexChanged(object sender, EventArgs e)
{
String CS = CnfigurationManager.ConnectionStrings
["MyDatabaseConnectionString1"].ConnectionString;
using (SqlConnection scon = new SqlConnection(CS))
{
sda = new SqlDataAdapter("Select * from Tramo", scon);
sda.Fill(ds, "Tramo");
// Do something.
if (ds.Tables.Contains("Tramo"))
{
testeeric.Text = DateTime.Now.ToString();
}
else
{
testeeric.Text = "Brasil";
}
}
}

Related

refreshing DataSource Master-Detail XtraGrid

i have this code that create Master-Detail XtraGrid at runtime
public partial class FRM_Reserved : DevExpress.XtraEditors.XtraForm
{
DataTable Table1 = new DataTable("Table1");
DataTable Table2 = new DataTable("Table2");
DataSet dataSet = new DataSet();
public FRM_Reserved()
{
InitializeComponent();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
dataSet.Relations.Add("OrderDetails",
dataSet.Tables["Table1"].Columns["Bon N"],
dataSet.Tables["Table2"].Columns["Bon N"]);
gridControl3.DataSource = dataSet.Tables["Table1"];
}
I want to refreshing DataSource on a click of button so I added this code
private void btnRefresh_Click(object sender, EventArgs e)
{
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.ForceInitialize();
}
but the code does not work ,can you help me please.
Try below code. Hope it works
private void btnRefresh_Click(object sender, EventArgs e)
{
gridControl3.DataSource=null;
gridControl3.Items.Clear();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.ForceInitialize();
}
the problem was in the name of the tables it change every time
dataSet.Tables[(Table1.TableName)]
dataSet.Tables[(Table2.TableName)]
so I made this changes
private void simpleButton1_Click(object sender, EventArgs e)
{
dataSet.Relations.Clear();
dataSet.Tables["Table2"].Clear();
dataSet.Tables["Table1"].Clear();
Table1 = ord.Get_Orders();
Table2 = ord.Get_Order_Res();
dataSet.Tables.Add(Table1);
dataSet.Tables.Add(Table2);
dataSet.Relations.Add("OrderDetails",
dataSet.Tables[(Table1.TableName)].Columns["Bon N"],
dataSet.Tables[(Table2.TableName)].Columns["Bon N"]);
gridControl3.DataSource = dataSet.Tables[(Table1.TableName)];
gridControl3.ForceInitialize();
}
Thanks for helping me
Use the following code
gridControl3.DataSource = dataSet.Tables["Table1"];
gridControl3.RefreshDataSource();
Try this one
private void button1_Click(object sender, EventArgs e)
{
var ds = new DataSet();
var dt1 = GetTable1Data();
var dt2 = GetTable2Data();
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
ds.Relations.Add("RelationTable",
ds.Tables["Table1"].Columns["col1"],
ds.Tables["Table2"].Columns["col1"]);
gridControl1.DataSource = ds.Tables["Table1"];
gridControl1.RefreshDataSource();
}
private DataTable GetTable1Data()
{
using (var conn = new SqlConnection("Conneciton string goes here"))
{
conn.Open();
using (var cmd = new SqlCommand("Stored procedure name goes here", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}
private DataTable GetTable2Data()
{
using (var conn = new SqlConnection("Conneciton string goes here"))
{
conn.Open();
const string sql = "SELECT * FROM Table2";
using (var cmd = new SqlCommand(sql, conn))
{
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}

Binding Combobox with database

I have combobox in my form which display value from database. I want one default value so I use .text property also and on selected index changed event the label display the corresponding value of the database the code is not working
string cstr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
private void AddStock_Load(object sender, EventArgs e)
{
bindcombo();
}
private void bindcombo()
{
SqlConnection con = new SqlConnection(cstr);
SqlDataAdapter da = new SqlDataAdapter("SELECT Dname FROM dealer", con);
DataTable dt = new DataTable();
da.Fill(dt);
cmbdealer.DataSource = dt;
cmbdealer.DisplayMember = "Dname";
cmbdealer.Text = "select-Dealer";
con.Close();
}
private void cmbdealer_SelectedIndexChanged(object sender, EventArgs e)
{
dealerdetails();
}
private void dealerdetails()
{
SqlConnection con = new SqlConnection(cstr);
SqlCommand cmd = new SqlCommand("select * from dealer where Dname='" + cmbdealer.Text + "'", con);
con.Open();
SqlDataReader re = cmd.ExecuteReader();
while (re.Read())
{
lbdl.Text = re["Ddlno"].ToString();
lbgst.Text = re["Dgstno"].ToString();
lbadd.Text = re["Daddress"].ToString();
}
}
the above code is working fine but when the form is load all the 3 label shows the database value of the first entry of my dealer table without selecting and value from combobox.

How to populate dependant dropdowns in Asp.Net C#

I want to populate TWO dropdownlist, based on selection of first dropdownlist the second dropdownlist will get populated.
Example :
Like i have two dropdownlist namely 1.ddlCountry and 2.ddlState
Now when country is selected then depending on the selected Country the States related with that Country will get populated in the State dropdownlist. I want to achieve this withour reloading the whole page in Asp.Net with coding language as C#.
How can i achieve the same?
Dropdownlist is fetching data from database by executing query.
You can use AJAX toolkit CascadingDropDown as told by Naresh.
OR
use ajax update panel and keep all Dropdowns in it. So the whole page will not load on changing dropdown value.
You didnt give the code to further solution.
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
FillStateByCountry();
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
FillLocationByCountryandState();
}
private void FillStateByCountry()
{
DataSet dstFillState;
int CountryId = Convert.ToInt32(ddlCountry.SelectedValue.ToString());
dstFillState = Tbl_State.FillDDLState(CountryId);
ddlState.DataSource = dstFillState;
ddlState.DataTextField = "State";
ddlState.DataValueField = "Id";
ddlState.DataBind();
}
similarly FillLocationByCountryandState();
Add two dropdownlists to your form and name it as cmbStates, cmbCities
when you select state name from cmbStates(dropwdownlist), cmbCities(dropdownlist) generates cities based on state name(cmbStates)
by fetching data from database
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=pbs-server;database=p2p;user id=shekar;password=sekhar#1346");
SqlCommand cmd = new SqlCommand("select states from Country", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "Country");
cmbStates.DataSource = ds.Tables[0];
cmbStates.SelectedValue = 0;
con.Close();
}
private void cmbStates_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=xxxx;database=xxxx;user id=xxxxr;password=xxxxxx");
SqlCommand cmd = new SqlCommand("select cities from States where cityname = 'cmbStates.SelectedItem.ToString()'", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "States");
cmbCities.DataSource = ds.Tables[0];
cmbCities.SelectedValue = 0;
con.Close();
}
OR
manually adding items
namespace DropDownlist
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmbStates.Items.Add("Andhra Pradesh");
cmbStates.Items.Add("Tamilnadu");
cmbStates.Items.Add("Karnataka");
cmbStates.SelectedValue = 0;
}
private void cmbStates_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbStates.SelectedItem.ToString() == "Andhra Pradesh")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Hyderabad");
cmbCities.Items.Add("Guntur");
cmbCities.Items.Add("Vijayawada");
cmbCities.SelectedValue = 0;
}
else if (cmbStates.SelectedItem.ToString() == "Tamilnadu")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Chennai");
cmbCities.Items.Add("Coimbatore");
cmbCities.Items.Add("ooty");
cmbCities.SelectedValue = 0;
}
else if (cmbStates.SelectedItem.ToString() == "Karnataka")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Bangalore");
cmbCities.Items.Add("Mangalore");
cmbCities.SelectedValue = 0;
}
else
{
MessageBox.Show("Please Select any value");
}
}
}
}

Grid View in Asp.net C# with wamp Server's MYSQL

I want to show my data in grid view in my Asp.new c# form.
I am using Wamp Server's MySQL database.
I have tired a lot for binding database with grid view.
Please do help.
my code :
public partial class Temp : System.Web.UI.Page
{
string conString = ConfigurationManager.ConnectionStrings["AASProject"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(conString);
con.Open();
gvFoodDetail.RowEditing+= new GridViewEditEventHandler(gvFoodDetail_RowEditing);
gvFoodDetail.RowDeleting += new GridViewDeleteEventHandler(gvFoodDetail_RowDeleting);
gvFoodDetail.RowUpdating += new GridViewUpdateEventHandler(gvFoodDetail_RowUpdating);
//gvFoodDetail_RowCancelingEdit += new GridViewCancelEditEventArgs(gv);
// gvFoodDetail.RowEditing += new GridViewEditEventHandler(gvFoodDetail_RowEditing);
// gvFoodDetail.RowDeleting += new GridViewDeleteEventHandler(gvFoodDetail_RowDeleting);
// gvFoodDetail.RowUpdating += new GridViewUpdateEventHandler(gvFoodDetail_RowUpdating);
// gvFoodDetail.RowCancelingEdit += new GridViewCancelEditEventHandler(gvFoodDetail_RowCancelingEdit);
gvFoodDetail.PageIndexChanging += new GridViewPageEventHandler(gvFoodDetail_PageIndexChanging);
if (!IsPostBack)
{
gvFoodDetail.Visible = true;
loadFoodDB();
}
}
public void loadFoodDB()
{
string getFoodDetails = "Select Emp_ID,intime,outtime,date From datetime";
MySqlConnection con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(getFoodDetails, con);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
gvFoodDetail.DataSource = dt;
gvFoodDetail.DataBind();
}
datagridview.Datasource = datasource
datagridview.databind()
This should set and show the data. You have to handle the columns and everything manually or automatically.

Gridview with DDl selected value

I had gridview which in load it will get data from database .And I added option for user to filter this grid view by DDl I did my code and the grid get data when load but when I selected DDl it didnot get any data and I made break point I noticed that Gridview1.Databind() hadnot any action on grid.So please any one help me
protected void Page_Load(object sender, EventArgs e)
{
DataTable DT = new DataTable();
if (DDlCity.SelectedIndex<0)
{
using (SqlConnection con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("GetDealers", con);
Com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter DA = new SqlDataAdapter(Com);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
}
protected void DDlCity_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable DT = new DataTable();
using (SqlConnection con = Connection.GetConnection())
{
SqlCommand Com = new SqlCommand("GetDealersByArea", con);
Com.CommandType = CommandType.StoredProcedure;
Com.Parameters.Add(Parameter.NewInt("#DEALERAREA_ID", DDlCity.SelectedValue));
SqlDataAdapter DA = new SqlDataAdapter(Com);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
i suppose you got confused on what i said...no worries
here is a working example of you give example code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridFunction();
}
}
private void BindGridFunction()
{
try
{
DataTable DT = new DataTable();
using (SqlConnection con = Connection.GetConnection())
{
if(DDlCity.SelectedIndex <0)
{
SqlCommand Com = new SqlCommand("GetDealers", con);
Com.CommandType = CommandType.StoredProcedure;
}
else
{
SqlCommand Com = new SqlCommand("GetDealersByArea", con);
Com.CommandType = CommandType.StoredProcedure;
Com.Parameters.Add(Parameter.NewInt("#DEALERAREA_ID", DDlCity.SelectedItem.Value));
}
SqlDataAdapter DA = new SqlDataAdapter(Com);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
catch(Exception ex)
{
DT = null; // etc...etc.. clear objects created
}
}
protected void DDlCity_SelectedIndexChanged(object sender, EventArgs e)
{
BindGridFunction();
}
I hope you get what i was trying to say. You can change the code according to you need.
Not tested yet but m sure will work.
Note : i woud suggest to use "DDlCity.SelectedItem.Value" instead of " DDlCity.SelectedValue"
In your post back you can put the binding code in condition
if (!IsPostBack){
// Bind grid here looking for or used call to function something like BindGrid()
}
and in BindGrid() function you can write binding code for grid view.
and on ddl selected index changed event you can again call the BindGrid() method to bind again accordingly.
also check that in your dropdownlist you have EnablePostBack - true.

Categories