Dynamically adding multiple rows in data table in C# - c#

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

Related

add data in DataTable for each button click

Hi all i have a form of data. each save button click ,I need to change in DataTable.
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("1"), new DataColumn("2"), new DataColumn("3")});
dt.Rows.Add( 1.Text, 2.Text, 3.Text);
}
currently last button click data only storing in data table .
how can I store all the button save data to this data table ?
I don't think that is good way
but work :
public static DataTable dt = new DataTable() { Columns = { new DataColumn("1"), new DataColumn("2"), new DataColumn("3") } };
protected void OnClick(object sender, EventArgs e)
{
dt.Rows.Add("1", "1", "1");
var count = dt.Rows.Count;
}
Result:

Get more information on GridView row click

I need to get this : When I click on a row, to get a more information about that particular file(every row represents one file from database), and that information is stored in different table... So, how is the best way to do this? Here you have a picture...
public partial class WebForm1 : System.Web.UI.Page
{
Web_service.WebService1SoapClient service;
protected void Page_Load(object sender, EventArgs e)
{
service = new Web_service.WebService1SoapClient();
BindData();
}
protected void BindData()
{
string strConnection = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand("select * from request", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow r in GridView1.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
r.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
r.Attributes["onmouseout"] = "this.style.textDecoration='none';";
r.ToolTip = "Click to select row";
r.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + r.RowIndex, true);
}
}
base.Render(writer);
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
}
}

How to edit the GridView

I want to edit the GridView without involving the database
protected void myGridView_RowUpdating(object sender,GridViewUpdateEventArgs e)
{
string reg = (myGridView.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)myGridView.Rows[e.RowIndex];
TextBox name = (TextBox)row.Cells[1].Controls[0];
TextBox email = (TextBox)row.Cells[2].Controls[0];
myGridView.EditIndex = -1;
BindGird();
}
this my bindgrid fucntion:
protected void BindGird()
{
DataTable dt = (DataTable)Session["myCart"];
this.myGridView.DataSource = dt; this.myGridView.DataBind();
}
and this is the row editing event
protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
myGridView.EditIndex = e.NewEditIndex; BindGird();
}

Adding new row to a DataTable

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.

Persisting DataTable or GridView DataSource

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.

Categories