Visual C# program saves only last index to XML file - c#

private void button1_Click(object sender, EventArgs e) //add data to listBox
{
if (String.IsNullOrWhiteSpace(textBox1.Text) || String.IsNullOrWhiteSpace(textBox2.Text))
{
MessageBox.Show("Proszę uzupełnić wszystkie pola, aby wprowadzić dane", "Błąd!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
listBox1.Items.Add(textBox4.Text + " " + textBox1.Text + " " + textBox2.Text);
listBox1.DisplayMember = textBox4.Text;
}
private void button2_Click(object sender, EventArgs e) //delete data from listbox
{
if(listBox1.SelectedIndex == -1)
{
MessageBox.Show("Proszę zaznaczyć pozycję by usunąć", "Błąd!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
listBox1.Items.Remove(listBox1.SelectedItem);
}
private void button3_Click(object sender, EventArgs e) //save to XML button
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.TableName = "Tabela";
dt.Columns.Add("Name");
dt.Columns.Add("Surname");
dt.Columns.Add("PESEL");
dt.Columns.Add("Room");
ds.Tables.Add(dt);
foreach (string item in listBox1.Items)
{
DataRow dr = ds.Tables["Tabela"].NewRow();
dr["Name"] = textBox1.Text;
dr["Surname"] = textBox2.Text;
dr["PESEL"] = textBox3.Text;
dr["Room"] = textBox4.Text;
ds.Tables["Tabela"].Rows.Add(dr);
}
ds.WriteXml("D:\\data.xml");
}
private void button4_Click(object sender, EventArgs e) //read from XML button
{
DataSet ds = new DataSet();
ds.ReadXml("D:\\data.xml");
foreach (DataRow item in ds.Tables["Tabela"].Rows)
{
listBox1.Items.Add(string.Format("{0} {1} {2}", item["Room"], item["Name"], item["Surname"]));
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml("D:\\data.xml");
foreach (DataRow item in ds.Tables["Tabela"].Rows)
{
textBox1.Text = item["Name"].ToString();
textBox2.Text = item["Surname"].ToString();
textBox3.Text = item["PESEL"].ToString();
textBox4.Text = item["Room"].ToString();
}
}
I have a problem while saving and reading XML file. When I will add some data to listBox from textBoxes is saves only last index I added, but multiple times.
Example:
<Tabela>
<Name>John</Name>
<Surname>Johnson</Surname>
<PESEL>123465789</PESEL>
<Room>21</Room>
</Tabela>
<Tabela>
<Name>John</Name>
<Surname>Johnson</Surname>
<PESEL>123465789</PESEL>
<Room>21</Room>
</Tabela>
<Tabela>
<Name>John</Name>
<Surname>Johnson</Surname>
<PESEL>123465789</PESEL>
<Room>21</Room>
</Tabela>
And when I load data from XML the listBox works fine, but when I selected one index from this list in my textBoxes appears only last index, not that I have clicked.

In your code you have
dr["Name"] = textBox1.Text;
dr["Surname"] = textBox2.Text;
dr["PESEL"] = textBox3.Text;
dr["Room"] = textBox4.Text;
For each itteration in the listbox items. As the textboxes wont be changing it will indeed add one for each item in your listbox.
Im thinking you needed to do something with item, in your for loop, not the text boxes

foreach (string item in listBox1.Items)
{
DataRow dr = ds.Tables["Tabela"].NewRow();
dr["Name"] = textBox1.Text;
dr["Surname"] = textBox2.Text;
dr["PESEL"] = textBox3.Text;
dr["Room"] = textBox4.Text;
ds.Tables["Tabela"].Rows.Add(dr);
}
I'm not sure what do you want to do but you would probably want to change something like reading and writing from a list or something.
If you tell us the technology that you are using (asp.net, wpf, etc.), we probably can help you out.

You are using a very bad approach with a listbox control that represents your main business entity. This is very bad...
In fact in order to make to work your solution, you should save into xml file everytime you add a new item data in the expected text boxes and the avoid to loop the listbox items when saving...
Then it is wrong also the method to display the details of your selected item when occurs the SelectedIndexChanged event, because you don't point to the correct listbox item selcted, but to the last saved item in the file everytime you select a new item in your listbox.
So, a better approach could be declare a class that will be your entity and a Collection of this class that will be the datasource of your listbox:
public class Booking{
string Name;
string Surname;
string PESEL; //your key? remember to manage duplicates if you insert manually (better if it were generated automatically as unique data (Guid))
string Room;
}
System.Collections.Generic.List<Booking> bookings; //instantiate in Form constructor method
then, your UI controls event handlers will manage this objects in order to do your operations, and so:
When you add a new item:
if (String.IsNullOrWhiteSpace(textBox1.Text) || String.IsNullOrWhiteSpace(textBox2.Text))
{
MessageBox.Show("Proszę uzupełnić wszystkie pola, aby wprowadzić dane", "Błąd!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
bookings.Add(new Booking{
Name = textBox1.Text,
Surname = textBox2.Text,
PESEL = textBox3.Text,
Room = textBox4.Text
});
listBox.DataSource = null;
listBox.DataSource = bookings; //use the datasource property
listBox.DisplayMember = "Room";
listBox.ValueMember = "PESEL";
When you delete one item:
if (listBox.SelectedIndex == -1) {
MessageBox.Show("Proszę zaznaczyć pozycję by usunąć", "Błąd!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
bookings.Remove(bookings.Find(c => c.PESEL == listBox.SelectedValue as string));
listBox.DataSource = null;
listBox.DataSource = bookings; //use the datasource property
listBox.DisplayMember = "Room";
listBox.ValueMember = "PESEL";
When you save your items:
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.TableName = "Tabela";
dt.Columns.Add("Name");
dt.Columns.Add("Surname");
dt.Columns.Add("PESEL");
dt.Columns.Add("Room");
ds.Tables.Add(dt);
foreach (Booking item in bookings)
{
DataRow dr = ds.Tables["Tabela"].NewRow();
dr["Name"] = item.Name;
dr["Surname"] = item.Surname;
dr["PESEL"] = item.PESEL;
dr["Room"] = item.Room;
ds.Tables["Tabela"].Rows.Add(dr);
}
ds.WriteXml("D:\\data.xml");
When you load from file
//attention to eventual new records appended to the list you may lose them
DataSet ds = new DataSet();
ds.ReadXml("D:\\data.xml");
bookings.Clear(); //<<== avoids dirty loading (duplicates)
foreach (DataRow item in ds.Tables["Tabela"].Rows) {
bookings.Add(new Booking() {
Name = item["Name"].ToString(),
Surname = item["Surname"].ToString(),
PESEL = item["PESEL"].ToString(),
Room = item["Room"].ToString()
});
}
listBox.DataSource = null;
listBox.DataSource = bookings; //use the datasource property
listBox.DisplayMember = "Room";
listBox.ValueMember = "PESEL";
When you want display details of a selcted listbox item:
Booking booking = bookings.Find(c => c.PESEL == listBox.SelectedValue as string);
if (booking == null) return;
textBox1.Text = booking.Name;
textBox2.Text = booking.Surname;
textBox3.Text = booking.PESEL;
textBox4.Text = booking.Room;
You may refactor the repetitive statements about listbox refreshing..

change listBox1_SelectedIndexChanged method in that way that the selected listbox value is used as filter for your table, something like this:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml("D:\\data.xml");
//split selected item by spaces
var values = listBox1.SelectedItem.ToString().Split(' ');
var selectedRow = ds.Tables["Tabela"].AsEnumerable()
.Where
(r => r["Room"].ToString() == values[0] &&
r["Name"].ToString() == values[1] &&
r["Surname"].ToString() == values[2]).FirstOrDefault();
if (selectedRow != null)
{
textBox1.Text = selectedRow["Name"].ToString();
textBox2.Text = selectedRow["Surname"].ToString();
textBox3.Text = selectedRow["PESEL"].ToString();
textBox4.Text = selectedRow["Room"].ToString();
}
}

Related

Writing in combobox

I have 3 comboboxes.
At first I imported the number of stations. Example 11650, 13450 and more.
When the user selects the number from the first combobox After automatically according to the station number in the second combobox After giving the date. Because each station dates are different.
My question to you is how I can do so if the user enters the number keys, in the second combobox to show dates?
My Code is :
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string MyConString1 = "SERVER=localhost;" +
"DATABASE=hydrodb;" +
"UID=root;" +
"PASSWORD=;";
MySqlConnection connection1 = new MySqlConnection(MyConString1);
string command1 = "select Dat FROM hydgod where Station=" + comboBox1.SelectedItem.ToString();
MySqlDataAdapter da1 = new MySqlDataAdapter(command1, connection1);
DataTable dt1 = new DataTable();
da1.Fill(dt1);
comboBox2.Items.Clear();
comboBox3.Items.Clear();
comboBox2.SelectedItem = -1;
comboBox3.SelectedItem = -1;
foreach (DataRow row in dt1.Rows)
{
string rowz = string.Format("{0}", row.ItemArray[0]);
comboBox2.Items.Add(rowz);
comboBox3.Items.Add(rowz);
}
connection1.Close();
}
I would suggest to get all corresponding dates into a List<string> and bind it as DataSource to the second ComboBox
List<string> dateList = new List<string>();
foreach (DataRow row in dt1.Rows)
{
dateList.Add(string.Format("{0}", row.ItemArray[0]);
}
comboBox2.DataSource = dateList;
EDIT:
I received the same values result in combobox. 2010-01-01 12:00:00AM
I want to cut the 12:00:00AM
If row.ItemArray[0] is of type DateTime you can try:
dateList.Add(row.ItemArray[0].ToString("yyyy-MM-dd));
if it is a simple string you can split it:
dateList.Add(row.ItemArray[0].Split(' ')[0]);
ps. to populate the 3-rd combobox also you can just hook the same List also to the 3-rd one:
comboBox3.DataSource = dateList;
Don't add the items manually and then hook the list to the DataSource. Do either or

Filtering combo box items using text search in C# windows form

I'm Trying to filter a combo box using its text property in all characters of Items not only Beginning of them. I'm trying below code in TextChanged event of my combo box. but unfortunately combo box resets after entering any key:
private void cmbCompany_TextChanged(object sender, EventArgs e)
{
string QueryCompany = string.Format("select id,title from acc.dl where title LIKE '%" + cmbCompany.Text + "%' union select null , null order by title");
SqlDataAdapter DA1 = new SqlDataAdapter(QueryCompany, con);
DataTable DT1 = new DataTable();
DA1.Fill(DT1);
cmbCompany.DisplayMember = "Title";
cmbCompany.ValueMember = "id";
cmbCompany.DataSource = DT1;
}
connection string "con" is defined and opened.
thanks for your helps.
Below part of code which works for me where searching part works not only at the begining but also in the middle. I paste also additional part responsible for move focus to the next control on the form after you hit enter button.
Initialization part:
public Form1()
{
InitializeComponent();
cmbItems = new List<ComboBoxItem>();
InitializeComboBox();
}
private void InitializeComboBox()
{
Random rand = new Random();
for (int i = 0; i <= 1500; i++)
{
int counter = rand.Next(1, 105000);
cmbItems.Add(new ComboBoxItem("randomNumber" + counter, "ID_" + counter));
}
comboBox1.DataSource = cmbItems;
}
Filtering part:
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
if (comboBox1.Text == string.Empty)
{
comboBox1.DataSource = cmbItems; // cmbItems is a List of ComboBoxItem with some random numbers
comboBox1.SelectedIndex = -1;
}
else
{
string tempStr = comboBox1.Text;
IEnumerable<ComboBoxItem> data = (from m in cmbItems where m.Label.ToLower().Contains(tempStr.ToLower()) select m);
comboBox1.DataSource = null;
comboBox1.Items.Clear();
foreach (var temp in data)
{
comboBox1.Items.Add(temp);
}
comboBox1.DroppedDown = true;
Cursor.Current = Cursors.Default;
comboBox1.SelectedIndex = -1;
comboBox1.Text = tempStr;
comboBox1.Select(comboBox1.Text.Length, 0);
}
}
Moving focus part:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\r') return;
if (this.ActiveControl != null)
{
this.SelectNextControl(this.ActiveControl, true, true, true, true);
}
e.Handled = true; // Mark the event as handled
}
I hope that helps someone.
you can add a textbox to your form and use it's text to filter :
string QueryCompany =
string.Format(
"select id,title from acc.dl where dltype in (2,4) union select null , null order by title");
SqlDataAdapter DA1 = new SqlDataAdapter(QueryCompany, con);
con.Open();
DataTable DT1 = new DataTable();
DA1.Fill(DT1);
con.Close();
DataView dv1 = new DataView(DT1);
dv1.RowFilter = "Title like '%" + txtCompany.Text + "%' or Title is null";
cmbCompany.DisplayMember = "Title";
cmbCompany.ValueMember = "id";
cmbCompany.DataSource = dv1;
and in selected index changed event :
txtCompany.Text = cmbCompany.Text;

DropDownListItems. Can't set any items to be disabled when bound to a datasource

I'm using the code below to grab a list of items from a database and bind them to a dropdownlist.
I insert separator lines in my itemlist and set
seperator.Attributes.Add("disabled", "true");
seperator.Enabled = false;
This should make the items non-selectable in the dropdown but it doesn't.
If I loop through my items after i've bound them, it does work. Surely I should be able to disable certain items before I bind them to a dropdownlist?
DropDownList gvCategory = (DropDownList)GridViewActvities.Rows[0].FindControl("gvCategory");
gvCategory.DataSource = formatCategoriesListItems();
gvCategory.DataBind();
public ListItemCollection formatCategoriesListItems()
{
OracleConnection sqlConn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString);
sqlConn.Open();
OracleCommand sqlSelect = new OracleCommand(#"SELECT ID, TASKGROUP, TASKCATEGORY FROM HOTT_GROUPS_CATS ORDER BY 'SORT'", sqlConn);
sqlSelect.CommandType = System.Data.CommandType.Text;
OracleDataAdapter sqlAdapter = new OracleDataAdapter(sqlSelect);
DataSet myDataset = new DataSet();
sqlAdapter.Fill(myDataset);
sqlConn.Close();
ListItemCollection listItems = new ListItemCollection();
//add blank item
listItems.Add(new ListItem(""));
string PreviousTaskGroup = "";
// database items to a list ready to bind to the dropdown
for (int i = 0; i < myDataset.Tables[0].Rows.Count; i++)
{
string TaskGroup= myDataset.Tables[0].Rows[i]["TASKGROUP"].ToString();
string TaskCategory = myDataset.Tables[0].Rows[i]["TASKCATEGORY"].ToString();
string TaskID= myDataset.Tables[0].Rows[i]["ID"].ToString();
// insert a seperator row based on the taskgroup
if (TaskGroup != PreviousTaskGroup)
{
ListItem seperator = new ListItem("--" + TaskGroup + "--", "");
seperator.Attributes.Add("disabled", "true");
seperator.Enabled = false;
listItems.Add(seperator);
if (i != myDataset.Tables[0].Rows.Count)
{
PreviousTaskGroup = myDataset.Tables[0].Rows[i]["TASKGROUP"].ToString();
i--;
}
}
else
{
listItems.Add(new ListItem(" " + TaskCategory, TaskID));
if (i != myDataset.Tables[0].Rows.Count)
{
PreviousTaskGroup = myDataset.Tables[0].Rows[i]["TASKGROUP"].ToString();
}
}
}
return listItems;
}
Unfortunately for your case, I don't think this is possible to do before a bind like that. Here is another question on the subject:
make drop down list item unselectable
Update:
I'm editing my answer based on Derrick's answer and your comment about it. Derrick is suggesting that after the dropdownlist is bound, then go through and disable the separators. So it would look something more like this:
protected void gvCategory_DataBound(object sender, EventArgs e)
{
foreach (ListItem li in gvCategory.Items)
{
if(li.Text.Contains("--"))
li.Attributes.Add("disabled", "true");
}
}
Update 2:
Add the OnDataBound event to manipulate the DropDownList after it is bound.
<asp:DropDownList ID="gvCategory" runat="server" OnDataBound="gvCategory_DataBound"></asp:DropDownList>
The markup should be generated using:
seperator.Attributes.Add("disabled", "disabled");
ASP.Net: How do I disable a ListItem?
Just have FormatCategoriesListItems return the data raw.
Handle gvCategory.Databind() yourself:
protected void gvCategory_DataBound(object sender, EventArgs e)
{
DataSet myDataset = gvCategory.DataSource as DataSet;
if (myDataset != null)
{
for (int i = 0; i < myDataset.Tables[0].Rows.Count; i++)
{
string TaskGroup = myDataset.Tables[0].Rows[i]["TASKGROUP"].ToString();
string TaskCategory = myDataset.Tables[0].Rows[i]["TASKCATEGORY"].ToString();
string TaskID = myDataset.Tables[0].Rows[i]["ID"].ToString();
// insert a seperator row based on the taskgroup
if (TaskGroup != PreviousTaskGroup)
{
ListItem seperator = new ListItem("--" + TaskGroup + "--", "");
seperator.Attributes.Add("disabled", "true");
seperator.Enabled = false;
listItems.Add(seperator);
if (i != myDataset.Tables[0].Rows.Count)
{
PreviousTaskGroup = myDataset.Tables[0].Rows[i]["TASKGROUP"].ToString();
i--;
}
}
else
{
listItems.Add(new ListItem(" " + TaskCategory, TaskID));
if (i != myDataset.Tables[0].Rows.Count)
{
PreviousTaskGroup = myDataset.Tables[0].Rows[i]["TASKGROUP"].ToString();
}
}
}
}

Cancel/insert/update not saving to the DB

I am working on Northwind database reproducing this demo. The code is not showing any error but all operations insert/update/delete are only temporary. If I add a record or cancel or update the next time I run the code, the content of the table is still the original one without any of the modification I did saved inthe db.
private static DataTable GetDataTable(string queryString)
{
String connString = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;
SqlConnection mySqlConnection = new SqlConnection(connString);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = new SqlCommand(queryString, mySqlConnection);
DataTable myDataTable = new DataTable();
mySqlConnection.Open();
try
{
mySqlDataAdapter.Fill(myDataTable);
}
finally
{
mySqlConnection.Close();
}
return myDataTable;
}
private DataTable Employees
{
get
{
object obj = this.Session["Employees"];
if ((!(obj == null)))
{
return ((DataTable)(obj));
}
DataTable myDataTable = new DataTable();
myDataTable = GetDataTable("SELECT * FROM Employees");
this.Session["Employees"] = myDataTable;
return myDataTable;
}
}
protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
this.RadGrid1.DataSource = this.Employees;
this.Employees.PrimaryKey = new DataColumn[] { this.Employees.Columns["EmployeeID"] };
}
protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
//Prepare new row to add it in the DataSource
DataRow[] changedRows = this.Employees.Select("EmployeeID = " + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["EmployeeID"]);
if (changedRows.Length != 1)
{
RadGrid1.Controls.Add(new LiteralControl("Unable to locate the Employee for updating."));
e.Canceled = true;
return;
}
//Update new values
Hashtable newValues = new Hashtable();
newValues["Country"] = (userControl.FindControl("TextBox7") as TextBox).Text;
newValues["City"] = (userControl.FindControl("TextBox8") as TextBox).Text;
newValues["Region"] = (userControl.FindControl("TextBox9") as TextBox).Text;
newValues["HomePhone"] = (userControl.FindControl("HomePhoneBox") as RadMaskedTextBox).Text;
newValues["BirthDate"] = (userControl.FindControl("BirthDatePicker") as RadDatePicker).SelectedDate.ToString();
newValues["TitleOfCourtesy"] = (userControl.FindControl("ddlTOC") as DropDownList).SelectedItem.Value;
newValues["Notes"] = (userControl.FindControl("TextBox1") as TextBox).Text;
newValues["Address"] = (userControl.FindControl("TextBox6") as TextBox).Text;
newValues["FirstName"] = (userControl.FindControl("TextBox2") as TextBox).Text;
newValues["LastName"] = (userControl.FindControl("TextBox3") as TextBox).Text;
newValues["HireDate"] = (userControl.FindControl("HireDatePicker") as RadDatePicker).SelectedDate.ToString();
newValues["Title"] = (userControl.FindControl("TextBox4") as TextBox).Text;
changedRows[0].BeginEdit();
try
{
foreach (DictionaryEntry entry in newValues)
{
changedRows[0][(string)entry.Key] = entry.Value;
}
changedRows[0].EndEdit();
this.Employees.AcceptChanges();
}
catch (Exception ex)
{
changedRows[0].CancelEdit();
Label lblError = new Label();
lblError.Text = "Unable to update Employees. Reason: " + ex.Message;
lblError.ForeColor = System.Drawing.Color.Red;
RadGrid1.Controls.Add(lblError);
e.Canceled = true;
}
}
protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
{
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
//Create new row in the DataSource
DataRow newRow = this.Employees.NewRow();
//Insert new values
Hashtable newValues = new Hashtable();
newValues["Country"] = (userControl.FindControl("TextBox7") as TextBox).Text;
newValues["City"] = (userControl.FindControl("TextBox8") as TextBox).Text;
newValues["Region"] = (userControl.FindControl("TextBox9") as TextBox).Text;
newValues["HomePhone"] = (userControl.FindControl("HomePhoneBox") as RadMaskedTextBox).Text;
newValues["BirthDate"] = (userControl.FindControl("BirthDatePicker") as RadDatePicker).SelectedDate.ToString();
newValues["TitleOfCourtesy"] = (userControl.FindControl("ddlTOC") as DropDownList).SelectedItem.Value;
newValues["Notes"] = (userControl.FindControl("TextBox1") as TextBox).Text;
newValues["Address"] = (userControl.FindControl("TextBox6") as TextBox).Text;
newValues["FirstName"] = (userControl.FindControl("TextBox2") as TextBox).Text;
newValues["LastName"] = (userControl.FindControl("TextBox3") as TextBox).Text;
newValues["HireDate"] = (userControl.FindControl("HireDatePicker") as RadDatePicker).SelectedDate.ToString();
newValues["Title"] = (userControl.FindControl("TextBox4") as TextBox).Text;
//make sure that unique primary key value is generated for the inserted row
newValues["EmployeeID"] = (int)this.Employees.Rows[this.Employees.Rows.Count - 1]["EmployeeID"] + 1;
try
{
foreach (DictionaryEntry entry in newValues)
{
newRow[(string)entry.Key] = entry.Value;
}
this.Employees.Rows.Add(newRow);
this.Employees.AcceptChanges();
}
catch (Exception ex)
{
Label lblError = new Label();
lblError.Text = "Unable to insert Employees. Reason: " + ex.Message;
lblError.ForeColor = System.Drawing.Color.Red;
RadGrid1.Controls.Add(lblError);
e.Canceled = true;
}
}
protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
{
string iD = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["EmployeeID"].ToString();
DataTable employeeTable = this.Employees;
if (employeeTable.Rows.Find(iD) != null)
{
employeeTable.Rows.Find(iD).Delete();
employeeTable.AcceptChanges();
}
}
Why my insert/delete/update are only temporary and visible in the current session? How can I fix this to get insert/update/delete changing the data in the database?
Acknowledge that Rows.Add() or AcceptChanges() do NOT write anything to the underlying database. They only operate on the in-memory data structures such as DataTables and DataSets. To actually save changes, you must:
Either use TableAdapter.Update() method and supply your modified DataTable to it.
Use SqlCommand and manually execute UPDATE, INSERT and DELETE commands.
You must NOT call AcceptChanges() before sending your changes back to the database.

After inserting/deleting datagridview not shows the inserted item

private void btndelete_Click(object sender, EventArgs e)
{
if (txtserch.Text == "")
{
MessageBox.Show("Enter Customer name to delete");
}
else
{
l1.conn();
SqlCommand cmd = new SqlCommand("delete from CUSTOMER where NAME='" + txtserch.Text + "'", l1.connection);
int a = cmd.ExecuteNonQuery();
if (a == 1)
{
MessageBox.Show("Deleted Sucessfully");
dataGridView1.Refresh();
dataGridView1.RefreshEdit();
dataGridView1.Update();
txtserch.Text = "";
}
else
{
MessageBox.Show("Customer Not Exist");
txtserch.Text = "";
}
}
}
DataGridView.Refresh() is graphics refresh, not data refresh.
Rebind your DatagridView to the source.
DataGridView dataGridView1 = new DataGridView();
dataGridView1.DataSource = source;
// Update Data in src1
dataGridView1.DataSource = null;
dataGridView1.DataSource = source;
In order to refresh your grid rebind it..
MyGridView.DataSource = ds;
MyGridView.DataBind();
here ds is the datasource which you are providing to grid.
Refer this link for details
If you want to Bind Data to Gridview after edit/delete/update actions,then you want to write below code of line
GridviewName.DataSource = ds;// retrieve the details and store in ds
GridViewName.DataBind();

Categories