I have a Click Event that fills a DataTable and the DataTable is the source of my GridView.
Then I have another click event that tries to get the GridView DataSource e converts it back to a DataTable Like:
DataTable dt = (DataTable)GridView1.DataSource;
But the Datasource returns null. Event if I put the code and the Page_Init event waiting for the right postBack
so I would like to know how can i persist the datasource of the gridview, or the DataTable
edited as required:
here is the whole code:
ps: the Page_Init was another try to get the datasource
private DataTable _dataTable;
public DataTable dataTable
{
get { return _dataTable; }
set { _dataTable = value; }
}
protected void Page_Init(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
string ctrlname = BLL.Common.GetPostBackControlId(this.Page);
if(ctrlname == "ButtonDownload")
{
DataTable dt = (DataTable)GridView1.DataSource;
}
}
}
protected void Filter_Click(object sender, EventArgs e)
{
string[] status = new string[2];
status[0] = "Paga";
status[1] = "Disponivél";
dataTable = BLL.PagSeguro.GetTransactions(TextBoxInicio.Text, TextBoxFim.Text, status);
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
protected void GetDataSource(object sender, EventArgs e)
{
DataTable dt = (DataTable)GridView1.DataSource;
}
This might work for you.
public partial class Demo : System.Web.UI.Page
{
private DataTable _myData = null;
protected DataTable MyData
{
get
{
if (null == _myData)
{
// You would load your data here.
_myData = new DataTable();
}
return _myData;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// Lets say you set your data source here
myGrid.DataSource = this.MyData;
}
protected void Rendering(object sender, EventArgs e)
{
// This is some other event that also needs to get at the data.
DataTable mydata = this.MyData;
}
protected void Unload(object sender, EventArgs e)
{
if (null != _myData)
{
_myData.Dispose();
_myData = null;
}
}
I'm pretty sure you can only access the datasource that way through the DataBound event or ItemDataBound event. You might be able to access the DataRowView for each item in the Items collection, but I'm not sure:
DataRow row = ((DataRowView)GridView1.Rows[0].DataItem).Row;
As for persisting the datasource, you need to consider whether that's a good idea. Your options for storing the datasource are Session or Cache, but if the result set is fairly small it might be more efficient to make another round trip when you need the datasource. Whatever you decide to do, don't store it in ViewState.
Related
I have two SP's, both doing different things but they are connected by the I.d's... how can i bind these so that the label changes with the dropdown selection?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Refreshdata(214, DateTime.Today, DateTime.Today.AddDays(1).AddMinutes(-1));
BindDropDownList();
LabelCount(214, DateTime.Today, DateTime.Today.AddDays(1).AddMinutes(-1));
}
}
private void BindDropDownList()
{
BizManager mgr = new BizManager();
DataView dv = mgr.GetItemSeriesMaster().DefaultView; //how to filter data
dv.RowFilter = ProductQueryFilter;
Dropdownlist1.DataSource = dv; //datasource == usp.getitemseriesmaster
Dropdownlist1.DataTextField = "Description"; // the items to be displayed in the list items
Dropdownlist1.DataValueField = "Id"; // the id of the items displayed
Dropdownlist1.DataBind();
}
private string ProductQueryFilter
{
get
{
return ConfigurationManager.AppSettings["ProductQueryFilter"];
} //returns itemseriesmaster 214 or 225 from web config key.
}
public void Refreshdata(int selectedProduct, DateTime shiftStart, DateTime shiftEnd)
{
BizManager biz = new BizManager();
GridView1.DataSource = biz.GetPacktstatisticsForShift( //passing in the usp
shiftStart
, shiftEnd
, selectedProduct).DefaultView; //passing in the parameters for the usp
GridView1.DataBind();
}
public void Dropdownlist1_SelectedIndexChanged(object sender, EventArgs e) //this fires after a DDL selection
{
DateTime shiftStart = DateTime.Today; //declaring the param at today - As below
DateTime shiftEnd = DateTime.Today.AddDays(1).AddMinutes(-1);
int productId; //declaring product ID
if (int.TryParse(Dropdownlist1.SelectedValue, out productId))
Refreshdata(productId, shiftStart, shiftEnd);
}
public void LabelCount(int seriesMasterId, DateTime shiftStart, DateTime shiftEnd)
{
{
}
So, i am really stuck here, my label is placed inside a form view as i only need one record that updates very regular. I know the bottom method is not a form view but i was hoping there maybe a work around without using the form view. But i do not see any way to do this even after hours of searching the internet.
I have listed employee names in one Dropdownlist. And by selecting any employee i am displaying employee details in gridview from database.
By default, dropdownlist have first item as selected item.So when i select another items it returns the first index only.
My Code:
protected void FilterBtn_Click(object sender, EventArgs e)
{
if (EmployeeList.SelectedIndex > -1)
{
sInitQuery = sInitQuery + " WHERE (EmployeeName ='" + EmployeeList.SelectedItem.ToString() + "')";
}
if (GlobalCS.OpenConnection() == true)
{
GridView1.DataSource = null;
GridView1.DataBind();
MySqlCommand cmd = new MySqlCommand(sInitQuery, GlobalCS.objMyCon);
MySqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
}
GlobalCS.CloseConnection();
EmployeeList.ClearSelection();
}
Put your page load code in if condition so it is just executed first time when page is loaded, other wise whenever post back happens page load gets called and your code will get executed which is the reason it gets set to first item everytime:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DisplayDatainGrid(); //All data in GridView
AddDataDropList(); //Load data in Dropdownlist
}
}
Currently every time your pageload code is exxecuting which should not happen.
Add EmployeeList.SelectedIndex to the ViewState.
protected void EmployeeList_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState.Add("employeeListIndex", EmployeeList.SelectedIndex);
}
Then, in Page_Load, read the ViewState and assign the value to EmployeeList.SelectedIndex.
void Page_Load(object sender, EventArgs e)
{
if(ViewState["employeeListIndex"] != null)
{
EmployeeList.SelectedIndex = ViewState["employeeListIndex"];
{
}
I'm new in this and I'm a little lost.
Trying to show the values of my database in textbox by selecting in the combobox. But I can't.
Please help me. This is my code:
private void CargarDatos()
{
string consulta = "SELECT * FROM [dbo].[alumno]";
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(Properties.Settings.Default.conexion);
SqlCommand cmd = new SqlCommand(consulta, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
con.Open();
da.Fill(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
this.dataGridView1.DataSource = dt;
cbalumno.DataSource = dt;
cbalumno.DisplayMember="Nombre";
cbalumno.ValueMember="Id";
}
private void Form1_Load(object sender, EventArgs e)
{
CargarDatos();
}
private void cbalumno_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
The parameters that i want to show are "Name" "Surname" and "DNI" of the table alumno.
Any ideas to how can I do that??
You can use DataRowView to get the record being bound with current SelectedItem. The Row property of DataRowView object will give you data row. Using this row you can get the columns being bound to it.
private void cbalumno_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView vrow = (DataRowView)cbalumno.SelectedItem;
string sValue = vrow.Row["Name"].ToString();
}
You already have placed the event cbalumno_SelectedIndexChanged in your code and now you have to use it.
Inside that event, just use the Text peroperty of that textbox and assign the value of the selected item in your combo box like this :
private void cbalumno_SelectedIndexChanged(object sender, EventArgs e)
{
yourTextBoxID.Text = comboBoxID.Text;
}
Hope this helps.
I have been tried to use the DATATABLE for storing the values for the entire application. I haven't use any database for storing values permanently. This are the dummy values I could use through out the application.
The issue is actually whenever I add a new row value into my DATATABLE it just overrides the previous values in the DATATABLE instead of adding an new row.
Is there any chance to add multiple rows to the DATATABLE dynamically and I can use it through out the application session.
** MY REGISTER PAGE**
public partial class _Default : System.Web.UI.Page
{
DataTable myDataTable;
protected void Page_Load(object sender, EventArgs e)
{
myDataTable = new DataTable();
myDataTable.Columns.Add("username");
myDataTable.Columns.Add("firstname");
myDataTable.Columns.Add("lastname");
myDataTable.Columns.Add("password");
myDataTable.Columns.Add("conpassword");
myDataTable.Columns.Add("email");
myDataTable.Rows.Add("kavi1", "kavi", "rajan", "123456", "123456", "kavi#gmail.com");
myDataTable.Rows.Add("sri1", "sri", "prem", "123456", "123456", "sri#gmail.com");
myDataTable.Rows.Add("mani1", "mani", "vanan", "123456", "123456", "mani#gmail.com");
HttpContext.Current.Session["name"] = myDataTable;
if (!IsPostBack)
{
if (Session["name"] != null)
{
myDataTable = Session["name"] as DataTable;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
myDataTable.Rows.Add(new object []{ TextBox1.Text ,TextBox2.Text,TextBox3.Text , TextBox4.Text,TextBox5.Text ,TextBox6.Text });
HttpContext.Current.Session["name"] = myDataTable;
if (Session["name"] != null)
{
Response.Write("success");
}
}
MY LOGIN PAGE
public partial class login : System.Web.UI.Page
{
DataTable dtResult;
protected void Page_Load(object sender, EventArgs e)
{
dtResult = (DataTable)Session["name"];
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < dtResult.Rows.Count; i++)
{
string un = dtResult.Rows[i].Field<string>("username");
string fn = dtResult.Rows[i].Field<string>("password");
if (TextBox1.Text == un && TextBox2.Text == fn)
{
//Response.Write("success");
Response.Redirect("home.aspx");
}
}
}
Issue:
At every Postback you are creating a new datatable and overriding it to the previous:
protected void Page_Load(object sender, EventArgs e)
{
myDataTable = new DataTable();
//....
HttpContext.Current.Session["name"] = myDataTable; //overriding to the previous
So when you click on the button to add the new row, it posts back, and recreates a new datatable and then add a new row to that table.
Solution:
You just need to modify the Page_Load event handler:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null) //this is you have to do at every postback
{
myDataTable = Session["name"] as DataTable;
}
if (!IsPostBack)
{
//if it is not post back, create a new DataTable and add values to it
myDataTable = new DataTable();
myDataTable.Columns.Add("username");
myDataTable.Columns.Add("firstname");
myDataTable.Columns.Add("lastname");
myDataTable.Columns.Add("password");
myDataTable.Columns.Add("conpassword");
myDataTable.Columns.Add("email");
myDataTable.Rows.Add("kavi1", "kavi", "rajan", "123456", "123456", "kavi#gmail.com");
myDataTable.Rows.Add("sri1", "sri", "prem", "123456", "123456", "sri#gmail.com");
myDataTable.Rows.Add("mani1", "mani", "vanan", "123456", "123456", "mani#gmail.com");
HttpContext.Current.Session["name"] = myDataTable;
}
}
I have a GeidView in my form and I have a button which add new records to the GridView by adding a row to a Datatable and then make this DataTable as the GridContol's Data Source.
The problem is when I add a new record it display in the GridView but when I add another rocord it doesn't display in the GridView, The GridView always contains the first row I added to the DataTable !
So please could you help me to solve this problem ?
This is the source code :
private DataTable recompensesTable;
private void AjoutLivre_Load(object sender, EventArgs e)
{
recompensesTable = MakeRecomponsesTable();
recompenseGridControl.DataSource = recompensesTable;
}
private DataTable MakeRecomponsesTable()
{
DataTable recmpensesTable = new DataTable("Recompenses");
var anneeColumn = new DataColumn();
anneeColumn.DataType = Type.GetType("System.Int32");
anneeColumn.ColumnName = "Année";
recmpensesTable.Columns.Add(anneeColumn);
var prixLiteraireColumn = new DataColumn();
prixLiteraireColumn.DataType = Type.GetType("System.String");
prixLiteraireColumn.ColumnName = "Prix Litéraire";
recmpensesTable.Columns.Add(prixLiteraireColumn);
return recmpensesTable;
}
private void nouveauRecompense_Click(object sender, EventArgs e)
{
DataRow row = recompensesTable.NewRow();
row[0] = ajoutRecompense.KeyWordAnnee;
row[1] = ajoutRecompense.KeyWordPrixLiteraire;
recompensesTable.Rows.Add(row);
recompenseGridControl.DataSource = recompensesTable;
}
In your Page_Load you have recompensesTable = MakeRecomponsesTable();. That overwrites the changes and recreate the datatable values
On page postback, variables are restored to their default values and they need to be recreated. You can use Session to maintain your values
private void AjoutLivre_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataTable recompensesTable = MakeRecomponsesTable();
Session["recompensesTable"] = recompensesTable; //Save it to session the first time
recompenseGridControl.DataSource = recompensesTable;
}
}
and retrieve the session preserved value
private void nouveauRecompense_Click(object sender, EventArgs e)
{
DataTable recompensesTable = (DataTable) Session["recompensesTable"]; //retrieve it from session
DataRow row = recompensesTable.NewRow();
row[0] = ajoutRecompense.KeyWordAnnee;
row[1] = ajoutRecompense.KeyWordPrixLiteraire;
recompensesTable.Rows.Add(row);
Session["recompensesTable"] = recompensesTable; //save it back to session
recompenseGridControl.DataSource = recompensesTable;
}
change your
private void AjoutLivre_Load(object sender, EventArgs e)
{
recompensesTable = MakeRecomponsesTable();
recompenseGridControl.DataSource = recompensesTable;
}
To
private void AjoutLivre_Load(object sender, EventArgs e)
{
if(!IsPostback)
recompensesTable = MakeRecomponsesTable();
recompenseGridControl.DataSource = recompensesTable;
}
You also must save the datatable to session
the recmpensesTable is always a new DateTable, you should save it to session for next use.