Data table in C#.net - c#

I have a problem related to DataTable in .net.
i am trying to fill datatable on page_load .that part is ok no issue datatable correctly filled up with data. but I noticed that when I clicked button on page... it again try to fill datatable which just a time-consuming task... I want datatable should fill once only ,when , when site open in browser .. not at every click ... because I have a large amount of data in table so it takes time to load in datatable..
plz help me out ...
here is my code:
protectd void Page_Load(object sender, EventArgs e)
{
cnn.ConnectionString= ConfigurationManager.ConnectionStrings["con"].ConnectionString;
// if (this.IsPostBack == true)
{
dr1 = TableUtoP();
dtWordsList.Load(dr1);
}
}
OleDbDataReader TableUtoPunj(String ArrWord)
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
}
cnn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "SELECT U, P from UtoP";
cmd.Connection = cnn;
OleDbDataReader dr = cmd.ExecuteReader();
return dr;
}

You need to check if the page is posting back or not, like this:
protected void Page_Load(object sender, EventArgs e)
{
cnn.ConnectionString= ConfigurationManager.ConnectionStrings["con"].ConnectionString;
if(!IsPostBack)
{
// This will only happen when the page is first loaded, as the first time is not considered a post back, but all others are
dr1 = TableUtoP();
dtWordsList.Load(dr1);
}
}

Only fill the dataTable if it's not a PostBack...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//TO DO: Make the call to fill the data table here
}
}

Related

Update Table only works once in datagridview (c#)

I have a datagridview in which I have made cells editable. Once the user has entered any text, they hit the "UPDATE" button, it updates the database.
The problem is whenever I open the application, it does update only for the first time. When I try to make more modification and click "UPDATE" button, it fails to update database. Here is my code. Please suggest any solution
private void Form1_Load_1(object sender, EventArgs e)
{
con.Open();
sda = new SqlDataAdapter("Select * from Name", con);
ds = new System.Data.DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
scb = new SqlCommandBuilder(sda);
sda.Update(ds);
}
Actually, there is nothing wrong with the code I mentioned. Instead there was some another section which was causing db not to be updated.
I also kept a Refresh button with this code -
private void button2_Click(object sender, EventArgs e)
{
sda = new SqlDataAdapter("Select * from Name", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
Seems that it reverted back Update to original db content. Removing it worked successfully.

dataadapter.update() does not save to database

The following code is not saving the changes from the dataset to the database via the dataadapter.update(). I display the data on a winform to text boxes.
I have a save button that should save the changes made to the database. the changes are only saved to the in memory copy of the dataset. what am i missing to get this to save the changes to the database?
public partial class Frm_Main : Form
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
BindingSource binding_Login = new BindingSource();
SqlCommandBuilder builder = new SqlCommandBuilder();
SqlConnection connection = new SqlConnection();
SqlCommand sqlcommand = new SqlCommand();
public Frm_Main()
{
InitializeComponent();
}
private void FrmMain_Load(object sender, EventArgs e)
{
this.Text = "Main (" + GlobalVars.username.ToString() + ")";
this.AcceptButton = btnSearch;
connection.ConnectionString = GlobalVars.sqlConnString;
}
private void FrmMain_Close(object sender, EventArgs e)
{
Close();
}
private void btnSearch_Click(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(txtSearch.Text))
{
Search();
}
}
public void Search()
{
string sqlcommandstring = "select * from login where loginname like #search;";
connection.Open();
sqlcommand.CommandText = sqlcommandstring;
sqlcommand.Connection = connection;
sqlcommand.Parameters.AddWithValue("#search", "%" + txtSearch.Text + "%");
adapter.SelectCommand = sqlcommand ;
builder.DataAdapter = adapter;
adapter.Fill(ds,"Login") ;
BindControls();
txtLoginName.DataBindings.Add(new Binding("Text", binding_Login, "LoginName"));
txtPassword.DataBindings.Add(new Binding("Text", binding_Login, "Password"));
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.DeleteCommand = builder.GetDeleteCommand();
adapter.InsertCommand = builder.GetInsertCommand();
}
private void btnNext_Click(object sender, EventArgs e)
{
binding_Login.MoveNext();
}
protected void BindControls()
{
binding_Login.DataSource = ds.Tables[0];
}
private void btnPrevious_Click(object sender, EventArgs e)
{
binding_Login.MovePrevious();
}
private void btnSave_Click(object sender, EventArgs e)
{
ds.AcceptChanges();
adapter.Update(ds.Tables[0]);
}
}
I was able to resolve the issue by changing the save buttons click event to the following:
private void btnSave_Click(object sender, EventArgs e)
{
this.binding_Login.EndEdit();
adapter.Update(this.ds.Tables[0]);
}
The problem was in this line:
private void btnSave_Click(object sender, EventArgs e)
{
ds.AcceptChanges();//EDIT This is the problem!
adapter.Update(ds.Tables[0]);
}
I had a similar problem and during debbuging I realized that if you call .AcceptChanges() before DataAdapter.Update(), all your modified rows will change their status to Unchanged. This means that DataAdapter.Update() will lose all the flags it needs to pick the right INSERT, UPDATE, DELETE command.
I also had problems using editing batches like:
row.BeginEdit();
// Modify several rows
row.EndEdit();
As I understand, the problem here happens because all changes are reserved until you call the AcceptChanges() method, thus causing all the row state flags to be set as Unchanged, making DataAdapter.Update() essentially blind.
In short:
Create a DataAdapter.
Set the InsertCommand, UpdateCommand, DeleteCommand, SelectCommand.
Fill a DataSet, DataTable, DataRow[], with the adapter.
Make changes to your DataSet, DataTable, DataRow[].
Make sure these changes are flagged in the RowState property of the modified row(s).
To ensure this, don't use batch editing, and don't call AcceptChanges(), before the DataAdapter.Update() method.
Using the same adapter, call adapter.Update(DataSet|DataTable|DataRow[]).

Annoying postback and paging issue

I asked a similar question to this but the circumstances have changed.
I bind my gridview through code rather than on the source.
The pagination works fine, but if I click a button on second page of the gridview (after pagination), the postback is causing the pagination to reset to page 1. Can anyone tell me what I'm doing wrong?
Within my pageload i have set the !POSTBACK method as shown i.e if there is postback event, then it shouldn't reset the grid but it does!
Heres the onload:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["usersName"] != null)
{
object a = Session["_id"];
IDMaster = Convert.ToInt32(a);
GridView1.Columns[10].Visible = true;
GridView1.Columns[11].Visible = true;
}
else
{
GridView1.Columns[10].Visible = false;
GridView1.Columns[11].Visible = false;
}
if (!IsPostBack)
{
BindGrid();
}
The BindGrid();
SqlConnection sqlcon = new SqlConnection(connstring);
SqlCommand sqlcmd = new SqlCommand("select * from Coffees ORDER BY coffeeName ASC", sqlcon);
SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
Page index method:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
if(ViewState["searchTerm"] != null)
{
object a = ViewState["searchTerm"];
string reloadTerm = a.ToString();
setGrid(reloadTerm);
}
You need to bind your gridview in GridView1_PageIndexChanging event
GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
if(ViewState["searchTerm"] != null)
{
object a = ViewState["searchTerm"];
string reloadTerm = a.ToString();
setGrid(reloadTerm);
}
BindGrid();
}
hopefully it works for you.
Since you are binding grid view dynamically, Please remove
if (!IsPostBack)
condition from page load. Grid view needs binding every time.
I found this issue. I forgot that after I add an item to my cart i was calling response.redirect to refresh the page....obviously this meant the page was recalled refreshing the page so the grid was always going to reset. Thanks again.

Master Detail in ASP.NET

I have two tables.
tbl_Request(PKRequestID, RequestCode) and tbl_Personnel(PKPersonID, PerosnelName FKRequestID)
FKrfequestID is a foreign key to tbl_request.
I have a grid view in Requests.aspx page that shows tbl_request records. There is a "New Item" button in this page too. When user clicks this button RequestInsert.aspx page opens. In this page user enters some data like RequestCode and hits the "Next" button and goes to Personel.aspx page which contains a gridview that shows the personnel who are related to the request. In this page user should define Personnel who are related to the request. When the whole process finishes user hits "save" button. Both tables will be update when user clicks on "save" button. How can I implement Personel.aspx page?
HERE IS AN APPROACH :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dttbl = new DataTable();
dttbl.Columns.Add("PKPersonID", System.Type.GetType("System.String"));
dttbl.Columns.Add("PerosnelName", System.Type.GetType("System.String"));
dttbl.Columns.Add("FKRequestID", System.Type.GetType("System.String"));
Session["MyDataTable"] = dttbl;
}
}
protected void btnok_Click(object sender, EventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
DataRow row1 = t.NewRow();
row1["PKPersonID"] = txtid.Text ;
row1["PerosnelName"] = txtname.Text;
row1["FKRequestID"] = Session["FKRequestID"];
t.Rows.Add(row1);
Session["MyDataTable"] = t;
GridView1.DataSource = t;
GridView1.DataBind();
}
protected void btnsave_Click(object sender, EventArgs e)
{
DataTable t2 = (DataTable)Session["MyDataTable"];
SqlConnection con = new SqlConnection("connection_string"
using (SqlCommand command = con.CreateCommand())
{
//Here you are inserting values to tbl_Request
if (con.State == 0)
con.Open();
command.CommandText = #"INSERT INTO tbl_Request (PKRequestID,RequestCode) VALUES (#PKRequestID,#RequestCode)";
command.Parameters.AddWithValue("#PKRequestID", Session["PKRequestID"]);
command.Parameters.AddWithValue("#RequestCode", Session["RequestCode"]);
command.ExecuteNonQuery();
}
foreach (DataRow row in t2.Rows)
{
//Here you are inserting values to tbl_Personnel
using (SqlCommand command2 = con.CreateCommand())
{
if (con.State == 0)
con.Open();
command2.CommandText = #"INSERT INTO tbl_Personnel (PerosnelName, FKRequestID) VALUES ( #PerosnelName, #FKRequestID)";
command2.Parameters.AddWithValue("#PerosnelName", txtname.Text);
command2.Parameters.AddWithValue("#FKRequestID", Session["PKRequestID"]);
command2.ExecuteNonQuery();
}
}
}

How to implement editing Master/Detail records?

I have two tables.
tbl_Request(PKRequestID, RequestCode) and tbl_Personnel(PKPersonID, PerosnelName FKRequestID)
FKrfequestID is a foreign key to tbl_request. I have a grid view in Requests.aspx page that shows tbl_request records. There is a "New Item" button in this page too. When user clicks this button RequestInsert.aspx page opens. In this page user enters some data like RequestCode and hits the "Next" button and goes to Personel.aspx page which contains a gridview that shows the personnel who are related to the request. In this page user should define Personnel who are related to the request. When the whole process finishes user hits "save" button. Both tables will be update when user clicks on "save" button. How can I implement Personel.aspx page?
Here is the code for personnelaspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dttbl = new DataTable();
dttbl.Columns.Add("PKPersonID", System.Type.GetType("System.String"));
dttbl.Columns.Add("PerosnelName", System.Type.GetType("System.String"));
dttbl.Columns.Add("FKRequestID", System.Type.GetType("System.String"));
Session["MyDataTable"] = dttbl;
}
}
protected void btnok_Click(object sender, EventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
DataRow row1 = t.NewRow();
row1["PKPersonID"] = txtid.Text ;
row1["PerosnelName"] = txtname.Text;
row1["FKRequestID"] = Session["FKRequestID"];
t.Rows.Add(row1);
Session["MyDataTable"] = t;
GridView1.DataSource = t;
GridView1.DataBind();
}
protected void btnsave_Click(object sender, EventArgs e)
{
DataTable t2 = (DataTable)Session["MyDataTable"];
SqlConnection con = new SqlConnection("connection_string"
using (SqlCommand command = con.CreateCommand())
{
//Here you are inserting values to tbl_Request
if (con.State == 0)
con.Open();
command.CommandText = #"INSERT INTO tbl_Request (PKRequestID,RequestCode) VALUES (#PKRequestID,#RequestCode)";
command.Parameters.AddWithValue("#PKRequestID", Session["PKRequestID"]);
command.Parameters.AddWithValue("#RequestCode", Session["RequestCode"]);
command.ExecuteNonQuery();
}
foreach (DataRow row in t2.Rows)
{
//Here you are inserting values to tbl_Personnel
using (SqlCommand command2 = con.CreateCommand())
{
if (con.State == 0)
con.Open();
command2.CommandText = #"INSERT INTO tbl_Personnel (PerosnelName, FKRequestID) VALUES ( #PerosnelName, #FKRequestID)";
command2.Parameters.AddWithValue("#PerosnelName", txtname.Text);
command2.Parameters.AddWithValue("#FKRequestID", Session["PKRequestID"]);
command2.ExecuteNonQuery();
}
}
}
How can I implement edit mode? In this mode I want users be able to delete personnel or add them?
Ok. You need to use session to store the tbl_Request.PKRequestID of the record that is to be edited when user clicks Edit button. After that re direct the user to a new page Edit_Requests_Personnel.aspx where you can edit the records.

Categories

Resources