I'm writing a program which add items to DataGridView and save the inputs to an xml file which is created by clicking button (if not exists). This works fine. But if I restart the program it should load every item to DataGridView. But I have to add a new item first and then all the other items are displayed. So the items won't load if Form1 load. I think I have to put some code in Form1_Load() but I don't have an idea. I tried to put XElement.Load(); in Form1_Load() but no success. Here you can see my code:
XElement xmlFile;
XElement xmlnode;
private void Form1_Load(object sender, EventArgs e)
{
xmlFile = XElement.Load(#"C:\Users\rs\Desktop\Save\save.xml");
xmlFile.Add(xmlnode);
}
private void btnSave_Click(object sender, EventArgs e)
{
if (!File.Exists(#"C:\Users\rs\Desktop\Save\save.xml"))
{
using (File.Create(#"C:\Users\rs\Desktop\Save\save.xml")) { }
}
xmlnode = new XElement("iToDo",
new XElement("Name", txtName.Text),
new XElement("Priority", comPrio.Text),
new XElement("StartDate", txtStart.Text),
new XElement("EndDate", txtEnd.Text),
new XElement("Comment", txtComment.Text)
);
try
{
xmlFile = XElement.Load(#"C:\Users\rs\Desktop\Save\save.xml");
xmlFile.Add(xmlnode);
}
catch (XmlException)
{
xmlFile = new XElement("ToDos", xmlnode);
}
xmlFile.Save(#"C:\Users\rs\Desktop\Save\save.xml");
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(#"C:\Users\rs\Desktop\Save\save.xml");
DataTable table = flatDataSet.Tables[0];
dataGridToDo.DataSource = table;
}
Someone got an idea or can give me a hint?
Thanks in advance
Cheers
You will have to put this in the form1_load method:
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(#"C:\Users\rs\Desktop\Save\save.xml");
DataTable table = flatDataSet.Tables[0];
dataGridToDo.DataSource = table;
I've created your app now, here's my Form1_Load method:
private void Form1_Load(object sender, EventArgs e)
{
xmlFile = XElement.Load(#"C:\save.xml");
xmlFile.Add(xmlnode);
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(#"C:\save.xml");
DataTable table = flatDataSet.Tables[0];
dataGridToDo.DataSource = table;
}
When I run the app, then my datagrid gets filled with the xml data.
Related
When I GridView data Update in other forms then data update but when close this form then gridview data refresh not response automatically in C# win-forms application
Here my Code:
private void button1_Click(object sender, EventArgs e)
{
aCatagory=new tbl_Catagory();
aContext = new RM_Inventory_DataContext();
var product = (from p in aContext.tbl_Catagories
where p.CatagoriesID == Convert.ToDecimal(textBox1.Text)
select p).Single();
product.CatagoriesName = textBox2.Text;
aContext.SubmitChanges();
this.Close();
AddCatagories addCatagories=new AddCatagories();
addCatagories.GridView();
}
public void GridView()
{
gridControl1.DataSource = new RM_PM_Inverntory_Management_System.RM_Inventory_DataContext().tbl_Catagories;
}
You are not binding gridview after assigning the datasource.
public void GridView()
{
gridControl1.DataSource = What ever Data Source You have
gridControl1.DataBind();
}
I'm writing a program in which i can add items to a DataGridView. This works perfectly. And I got a Delete button, to remove the items from DataGridView. This is working, but not perfectly. It delets my items but if I restart the program, the items are still here. I'm saving the items to an xml file. So here you can see my code for adding items to DataGridView:
private void btnSave_Click(object sender, EventArgs e)
{
if (!File.Exists(#"C:\Users\rs\Desktop\Save\save.xml"))
{
using (File.Create(#"C:\Users\rs\Desktop\Save\save.xml")) { }
}
xmlnode = new XElement("iToDo",
new XElement("Name", txtName.Text),
new XElement("Priorität", comPrio.Text),
new XElement("Anfangsdatum", txtStart.Text),
new XElement("Enddatum", txtEnd.Text),
new XElement("Bemerkung", txtComment.Text)
);
try
{
xmlFile = XElement.Load(#"C:\Users\rs\Desktop\Save\save.xml");
xmlFile.Add(xmlnode);
}
catch (XmlException)
{
xmlFile = new XElement("ToDos", xmlnode);
}
xmlFile.Save(#"C:\Users\rs\Desktop\Save\save.xml");
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(#"C:\Users\rs\Desktop\Save\save.xml");
DataTable table = flatDataSet.Tables[0];
dataGridToDo.DataSource = table;
}
And here you can see my code for deleting rows:
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in this.dataGridToDo.SelectedRows)
{
dataGridToDo.Rows.RemoveAt(row.Index);
}
}
And I tried to put this in Form_Closing(), which not works:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = false;
Application.Exit();
}
Can someone give me a hint how I can fix this?
Thanks in advance
Cheers
ehm.. I'm a bit puzzled by your FormClosing code. You write the xml file from xmlFile and immediately read it again? On the form closing the result of reading it in would superfluous as the data grid will be destroyed quit
I am using DevExpress in my winform application, I have a gridview, data entry form, datanavigator, all bound to dataset.
I want to add new record, if using datanavigator "Add" it works good, how to do the same using a "New Record" button?
BindingSource.AddNew()
is not working, it usually does, but with devexpress its not working.
If you want to use binding then use your objects with binding source..
and use the binding list .AddingNew += new AddingNewEventHandler(listOfParts_AddingNew);
event to add new entity object ..
See the example of BindingList on MSDN.
void listOfParts_AddingNew(object sender, AddingNewEventArgs e)
{
e.NewObject = new Part(textBox1.Text, int.Parse(textBox2.Text));
}
DevExpress WinForm Controls works so fast with binding sources as compare to typed datasources etc... YOu can implement bindingSources using these example..
set gridview and the associcated controls datasource to bindsouce that you have created...
process your form with the this MSDN example..
have a look on this code snippet.. may be you will get some idea from this..
private void BindingLIstDemo_Load(object sender, EventArgs e)
{
InitializeListOfEmployees();
BindlstEmp();
listofEmp.AddingNew += new AddingNewEventHandler(listOfEmp_AddingNew);
listofEmp.ListChanged += new ListChangedEventHandler(listofEmp_ListChanged);
}
private void BindlstEmp()
{
lstEmpList.Items.Clear();
lstEmpList.DataSource = listofEmp;
lstEmpList.DisplayMember = "Name";
}
void listofEmp_ListChanged(object sender, ListChangedEventArgs e)
{
MessageBox.Show(e.ListChangedType.ToString());
//throw new NotImplementedException();
}
//declare list of employees
BindingList<Emp> listofEmp;
private void InitializeListOfEmployees()
{
//throw new NotImplementedException();
// Create the new BindingList of Employees.
listofEmp = new BindingList<Emp>();
// Allow new Employee to be added, but not removed once committed.
listofEmp.AllowNew = true;
listofEmp.AllowRemove = true;
// Raise ListChanged events when new Employees are added.
listofEmp.RaiseListChangedEvents = true;
// Do not allow Employee to be edited.
listofEmp.AllowEdit = false;
listofEmp.Add(new Emp(1, "Niranjan", 10000));
listofEmp .Add (new Emp (2,"Jai", 8000));
}
// Create a new Employee from the text in the two text boxes.
void listOfEmp_AddingNew(object sender, AddingNewEventArgs e)
{
e.NewObject = new Emp (Convert.ToInt32(txtId.Text), txtName.Text,Convert.ToInt32(txtSalary.Text));
}
private void btnAdd_Click(object sender, EventArgs e)
{
Emp empItem = listofEmp.AddNew();
txtId.Text = txtName.Text = txtSalary.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
Form1 obj = new Form1();
obj.Show();
}
private void btnDelete_Click(object sender, EventArgs e)
{
var sg = (from sc in listofEmp.ToList<Emp>() where sc.Name == ((Emp)lstEmpList.SelectedValue).Name select sc);
}
private void lstEmpList_SelectedIndexChanged(object sender, EventArgs e)
{
Emp se = listofEmp[lstEmpList.SelectedIndex];
txtId.Text = se.Id.ToString();
txtName.Text = se.Name;
txtSalary.Text = se.Salary.ToString();
}
Here I am using BindingList as datasouce BindingList<Emp> listofEmp; and on the place of grid listing of records are shown in a listbox control.. but all same...try this with your gridview..
Ok so I have made a DataSet that reads the data hardcoded but unsure how I can read input from user to replace that hardcoded data.
I have a form with a textbox and submit button, I want to save data to xml after going through my DataSet.
Kinda new to programming, hoping someone can give me some pointers here.
public partial class Form1 : Form
{
// DataSet
DataSet ds = new DataSet();
DataColumn email = new DataColumn();
public Form1()
{
InitializeComponent();
email = new DataColumn("Email", Type.GetType("System.String"));
ds.dt.Rows.Add(0, "my_email");
ds.dt.Rows.Add(1, "my_email");
var results = from myRow in ds.dt
orderby myRow.id
where myRow.id == 0
select myRow;
foreach (var item in results)
{
ds.dt.WriteXml("email.xml");
}
}
}
Not really sure what you're trying to do without further information.
Maybe this will get you a bit further?
public partial class Form1 : Form
{
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
ds.Tables.Add("dt");
ds.Tables[0].Columns.Add("id");
ds.Tables[0].Columns.Add("email");
}
private void button1_Click(object sender, EventArgs e)
{
int count = ds.Tables[0].Rows.Count;
ds.Tables[0].Rows.Add(count, textBox1.Text);
}
private void button2_Click(object sender, EventArgs e)
{
ds.Tables[0].WriteXml("email.xml");
}
}
One textbox for input, one button for adding items to the dataset from the inputbox and one button for writing the xml to a file.
First of all:
_ddlOptions is drop down list
_selectedOptions is repeater control
and it's just provisional code of my final control.
What I want to do is to get data for _ddlOption on !IsPostBack. There is Add button that enables user to move selected drop down item to repeater control.
It the following way of updating Repeater.Items correct? I found many solution of adding/removing elements manually using DataSource, but here my DataSource is null, as I set it only on !IsPostBack.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
_ddlOptions.DataSource = new[] { 1, 2, 3 };
_ddlOptions.DataBind();
}
}
protected void OnAdd(object sender, EventArgs e)
{
var list = new ArrayList(_selectedOptions.Items);
list.Add(_ddlOptions.SelectedItem);
_ddlOptions.Items.RemoveAt(_ddlOptions.SelectedIndex);
_selectedOptions.DataSource = list;
_selectedOptions.DataBind();
}
If you only need to fetch data once and you're going to use viewstate, get the data first time you need it, store it in VS and get it from VS for all future PostBacks.
Example:
public List<int> Data
{
get
{
if (ViewState["Data"] == null)
{
// Get your data, save it and return it.
var data = new List<int> { 1, 2, 3 };
ViewState["Data"] = data;
return data;
}
return (List<int>)ViewState["Data"];
}
set
{
ViewState["Data"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData(Data);
}
}
private void BindData(List<int> data)
{
_ddlOptions.DataSource = data;
_ddlOptions.DataBind();
}
protected void OnAdd(object sender, EventArgs e)
{
var existing = Data;
existing.Add(_ddlOptions.SelectedItem);
_ddlOptions.Items.RemoveAt(_ddlOptions.SelectedIndex);
Data = existing;
BindData(existing);
}
I didn't test this - and its only my first thought but you can build on it from here.
Patrick.
Looks good to me. You just may want to move the decalration for your list outside the onAdd method. As you have it I think it will be reinitialized every time the add button is clicked, so you'll never have more than the currently selected item in your repeater.
You can use a DataAdapter to fill a table in a DataSet.
DataSet ds = new DataSet();
using (SqlConnection conn = YourConnectionFactory.GetConnection())
{
SqlCommand objComm = DBHelper.CreateStoredProc("YourStoredProcedure",
conn);
SqlDataAdapter adapt = new SqlDataAdapter(objComm);
adapt.Fill(ds, TableName);
conn.Close();
}
DataTable dt = ds.Tables[0];
for (int a=dt.Rows.Count-1; a>= 0; a--)
{
// check and insert as necessary
}
YourControl.DataSource = ds;
YourControl.DataBind();
You can also do something like this then,
like rebind Taken from: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx:
Dim values As New ArrayList()
values.Add(New PositionData("Microsoft", "Msft"))
values.Add(New PositionData("Intel", "Intc"))
values.Add(New PositionData("Dell", "Dell"))
Repeater1.DataSource = values Repeater1.DataBind()
Repeater2.DataSource = values Repeater2.DataBind()