Background:
Two buttons on a ASP.NET page.
Button 1:
Data is loaded into a DataSet.
2 Session variables, Session["a"] and Session["b"] are assigned the DataSet.
Button 2:
Session["a"] is cast to a DataSet. A record is deleted from the DataSet.
Issue:
BEFORE the AcceptChanges() function is called, both Session variables are changed to reflect the delete action (Rows.Count is 1 less). Why does this happen?
Surely the DataSet "ds" could not exist anymore?
protected void Button1_Click(object sender, EventArgs e)
{
string StringContainingSQLConnection = #"server=someserver;database=Standby;uid=StandbyUser;password=pass;";
SqlDataAdapter adp = new SqlDataAdapter("select * from CoreData", StringContainingSQLConnection);
DataSet ds = new DataSet();
adp.Fill(ds);
Session["a"] = ds;
Session["b"] = ds;
}
protected void Button2_Click(object sender, EventArgs e)
{
DataSet ds = ((DataSet)Session["a"]);
foreach (DataRow drw in ds.Tables[0].Rows)
{
drw.Delete();
ds.AcceptChanges();
Session["a"] = ds;
break;
}
}
I removed the conditional IF statement in the foreach loop for clarity and just delete the first record to prove the point.
Session a and Session b hold a reference to the location of the dataset in memory. So essentially a and b are just two different names for the same thing.
https://msdn.microsoft.com/en-us/library/490f96s2.aspx
If you wish for b to remain unchanged, you can create two datasets with the same initial data. Assign one set to a and one set to b.
Related
I am trying to get my datagridview to refresh on a timer but unable to figure it out
I have done a lot of googling and a youtube videos and cant find the fix.
private void Timer1_Tick(object sender, EventArgs e)
{
FillDataGridView();
}
private void FillDataGridView()
{
DataSet objDs = new DataSet();
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["con2"].ConnectionString);
MySqlDataAdapter myCommand;
string select = "select * from CadCall";
myCommand = new MySqlDataAdapter(select, con);
myCommand.SelectCommand.CommandType = CommandType.Text;
con.Open();
myCommand.Fill(objDs);
dataGridView2.DataSource = objDs;
dataGridView2.Update();
dataGridView2.Refresh();
}
In the end I want the datagridview to refresh when the timer hits 0 (every 100 miliseconds)
I think you might regret such a short refresh interval. Make it 10 seconds, and don't forget to close/dispose your connection afterwards or your program will soon crash. The update and refresh invocations are unnecessary
A dataset is a collection of datatables, and a datagridview is intended to show the contents of only one table. A dataset hence cannot be a DataSource for a datagridview without the DataMember property being set, and I'm not really sure what your table name would be so I recommend alternatively that you make the DataSource one of the tables in the dataset, or use a datatable instead of a dataset:
DataTable objDT = new DataTable();
datagridview2.DataSource = objDT;
OR
DataSet objDs = new DataSet();
datagridview2.DataSource = objDS.Tables[0];
Oh and make sure you actually enabled the timer; they're enabled=false by default
I have a DataGridView populated with a DataSet from my Database. I am trying to make changes in the DataGridView and apply those changes to the Database whenever I press 'Enter'.
Iv read alot of this same question, and researched the topic, but am still having trouble figuring out why I cannot apply changes made in my DataGridView to my Database. (I know this has been asked before, but still cant figure this out).
Can anyone show me what im doing wrong?
DataSet ds = new DataSet();
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlDataAdapter da;
public ListForm()
{
//Setting up DataGridView with data.
InitializeComponent();
da = new SqlDataAdapter("Select * from Contact_List", constring);
SqlCommandBuilder cmb = new SqlCommandBuilder(da);
da.UpdateCommand = cmb.GetUpdateCommand();
da.Fill(ds, "Contact_List");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Contact_List";
}
//Trying to update database with DataAdapter
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
//I believe that the changes to the database should be applied here
//Buts its not working
da.Update(ds, "Contact_List",);
ds.AcceptChanges();
con.Close();
}
}
You should end current edit before trying to save changes:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var cm = dataGridView1.BindingContext[ds, "Contact_List"];
cm.EndCurrentEdit();
da.Update(ds, "Contact_List");
}
Some other notes
You don't need a DataSet. A DataTable is enough.
When you create a SqlCommandBuilder by passing a SqlDataAdapter to the constructor, all insert, update and delete commands will be generated automatically and you don;t need to do anything yourself, so GetUpdateCommand() is not necessary.
Calling EndCurrentEdit cause the changes which you made on an IEditableObject be saved to underlying data source. DataRowView which is the object behind rows of grid is an IEditableObject and you should call EndCurrentEdit of the currency manager which cause EndEdit of DataRowView be called and commits changes to the underlying DataRow and ends the editing session.
If you bind the grid to a BindingSource, calling EndEdit of BindingSource will do the same.
After saving data, you don't need to call AcceptChanges manually.
You need to add exception handling to code.
it's because you're using SqlCommandBuilder, I haven't used it in a long time and I'm looking for more info, but I believe you can only update one table, no joins, and there has to be a unique key defined, otherwise you may want to generate your UPDATE statement manually.
reference
I have created a DataGrid and I take the data from database and put it in there.All the data retrieval are done by dynamically in the code behind.Here is a some portion of my code.
SqlConnection con = new SqlConnection("Data Source=PUNUTHL\\SQL;Initial Catalog=mytest;Integrated Security=True");
SqlDataAdapter ad;
DataSet ds = new DataSet();
static DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ad = new SqlDataAdapter("Select * from product",con);
ad.Fill(ds);
dt = ds.Tables[0];
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
}
}
Upto this point it works perfectly.
But I wanted to add the edit function for that DataGrid
But according to my query I took the "product_ID" values as well which can not allows to be updated.
Since I use both "Etid" and "Delete" commands, "prodcut-id" may be my 3rd column as shown in the picture.
So I wanted to be that column read only when the client hit on the edit button.So how can I tackle this problem.Are there any way to get the column names or column indexed?Please can some one help me.
This is one of the way to make a column at any index readonly.
DT.Columns(0).ReadOnly = True '// Make the column(0) readonly and assign to DataGrid.
Datagrid!.DataSource = DT
where DT is datatable used to collect the data from database and is datasource to the datagrid Datagrid1.
For further editing make the column readonly= false and make changes and again turn it into readonly.
Here in your case you can make your Id column that is 2 as readonly
I can't fix this error that I get A Relation named 'PlaneAirline' already belongs to this DataSet. I have tried to change the name of the relation but I get the same error
Here is my code:
private void getData()
{
SqlDataAdapter parentDataAdapter = new SqlDataAdapter("select * from Airline", connection);
parentDataAdapter.Fill(ds, "Airline");
SqlDataAdapter childDataAdapter = new SqlDataAdapter("select * from Plane", connection);
childDataAdapter.Fill(ds, "Plane");
DataColumn parentColumn = ds.Tables["Airline"].Columns["airline_id"];
DataColumn childColumn = ds.Tables["Plane"].Columns["airline_id"];
rel = new DataRelation("PlaneAirline", parentColumn, childColumn);
ds.Relations.Add(rel);
parentBindingSource.DataSource = ds;
parentBindingSource.DataMember = "Airline";
childBindingSource.DataSource = parentBindingSource;
childBindingSource.DataMember = "PlaneAirline";
}
private void dg_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void AirlineReservation_Load(object sender, EventArgs e)
{
parentDataGridView.DataSource = parentBindingSource;
childDataGridView.DataSource = childBindingSource;
getData();
}
Could you please help me
I think your problem is that you are calling GetData() method on CellContentClick event. This event will get fired when the content within a cell is clicked. Hence whenever you are clicking the cell your code is trying to add a relation which is already present when you first clicked a cell.
Probably you need to move the GetData() call to Form Load as given in the tutorial you have given.
Hope this helps.
On every click in your DataGrid (I'm assuming that dg_CellContentClick is tha click handler for the data grid cell) you're calling getData, where you try to add the relation PlaneAirlineover and over again.
Try to move the lines
rel = new DataRelation("PlaneAirline", parentColumn, childColumn);
ds.Relations.Add(rel);
to where you initially create or define your variable ds (I think it's a DataSet).
I have a DataSet + TableAdapter and bound dataGridView. I have an edit button which opens a new form with details to edit (WinForms). How do I refresh one row (selected one) in the Dataset and in dataGrid from database before opening the new form?
Example: Two users A and B. User A changed record ID(10) and user B still has the old value in record ID(10). User B presses edit button and should get fresh data from database (data after change made by user A).
string sql = "SELECT * FROM Orders";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
da.Fill(ds, "Orders");
connection.Close();
dataGridView1.DataSource = ds;
.....
private void button1_Click(object sender, EventArgs e)
{
//?
//refresh selected row in datagrid (from current database record)
//?
EditForm()
}
Create a new query in your TableAdapter that should only get one row and call it with just the primary key of the row you already have.
Plug the result into a new DataSet and grab the first row (after checking for Rows.Count() > 0)
I would enclose the populating the gridview bit in it's own method say something like fill_grid(). Then just call the method in the edit link click event. Then whatever has changed will update. Then add the method to all the other button link events too. Then every time the user is clicking a link the grid "refreshes" essentially.
For those who is looking for the answer in 2019,
assuming dataAdapter is a defined earlier class member
private void ButtonUpdate_Click(object sender, RoutedEventArgs e)
{
if (dataGrid.SelectedItem is DataRowView view)
{
DataRow currentRow = view.Row;
DataTable table = currentRow.Table;
dataAdapter.Fill(table.Rows.IndexOf(currentRow), 1, table);
}
}