C# - Grabbing Input > DataSet > XML - c#

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.

Related

Cannot select specific row on Janus GridEX

So I'm accessing a DB through a stored procedure and am able to pull the data I wanted into a popup box. The problem now is that no matter what row I click on, the SAME data keeps populating my fields. How the heck can I choose a particular row, and have that specific row's data pulled from the DB? Thanks for any help
Form1
public partial class DSC_Mon : Form
{
DSCU_SvcConsumer.MTCaller Caller;
DataSet dsZA;
DataSet dsOut;
public DSC_Mon()
{
InitializeComponent();
Caller = new DSCU_SvcConsumer.MTCaller();
dsZA = new DataSet();
dsOut = new DataSet();
}
private void DSC_Mon_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void LoadData()
{
if (!dsZA.Tables.Contains("Query"))
{
DataTable dtZA = dsZA.Tables.Add("Query");
dtZA.Columns.Add("str");
dtZA.Rows.Add(string.Format(#"exec MON_GetStatus"));
}
//dtZA.Rows.Add(string.Format(#"select * from am_company"));
dsOut.Clear();
dsOut.Merge(Caller.CallRequest("ZuluAction", dsZA));
if (gridEXMon.DataSource == null)
{
gridEXMon.DataSource = dsOut;
gridEXMon.DataMember = "Table";
}
//gridEXMon.RetrieveStructure();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
LoadData();
timer1.Enabled = true;
}
private void gridEXMon_DoubleClick(object sender, EventArgs e)
{
ReportInfo report = new ReportInfo();
report.ShowDialog();
}
}
I replaced the private void gridEXMon_DoubleClick with:
private void gridEXMon_RowDoubleClick(object sender, Janus.Windows.GridEX.RowActionEventArgs e)
{
if (e.Row.RowIndex < 0)
return;
int rowIndex = Convert.ToInt32(e.Row.RowIndex);
ReportInfo report = new ReportInfo(rowIndex);
report.ShowDialog();
}
Popup Dialog
public partial class ReportInfo : Form
{
public ReportInfo()
{
InitializeComponent();
DSCU_SvcConsumer.MTCaller caller = new DSCU_SvcConsumer.MTCaller();
DataSet dsZA = new DataSet();
DataSet dsOut = new DataSet();
if (!dsZA.Tables.Contains("Query"))
{
DataTable dtZA = dsZA.Tables.Add("Query");
dtZA.Columns.Add("str");
dtZA.Rows.Add(string.Format(#"MON_ReportInfo"));
}
dsOut.Clear();
dsOut.Merge(caller.CallRequest("ZuluAction", dsZA));
DataTable dt = dsOut.Tables["Table"];
DataRow dr = dt.Rows[0];
if (dt != null)
{
systemNameTextBox.Text = dr["System"].ToString();
contactName1TextBox.Text = dr["Manager"].ToString();
functionNameTextBox.Text = dr["Function"].ToString();
durationMSTextBox.Text = dr["Speed"].ToString();
}
}
I then sent the rowIndex to the popup:
DataTable dt = dsOut.Tables["Table"];
DataRow dr = dt.Rows[rowIndex];
systemNameTextBox.Text = dr["System"].ToString();
contactName1TextBox.Text = dr["Manager"].ToString();
functionNameTextBox.Text = dr["Function"].ToString();
durationMSTextBox.Text = dr["Speed"].ToString();
}
Better to get the data from the grid to save the extra call to the database in your ReportInfo class.
Here is the code:
private void gridEXMon_DoubleClick(object sender, EventArgs e)
{
if (e.Row.RowIndex < 0)
return;
ReportInfo report = new ReportInfo();
String System = Convert.ToInt32(e.Row.Cells["System"].Value);
String Manager = Convert.ToString(e.Row.Cells["Manager"].Value);
String Function = Convert.ToDecimal(e.Row.Cells["Function"].Value);
String Speed = Convert.ToInt32(e.Row.Cells["Speed"].Value);
report.ShowDialog(System, Manager, Function, Speed);
}
Then your ReportInfo class ctor should be:
public partial class ReportInfo : Form
{
public ReportInfo(String System, String Manager, String Function, String Speed)
{
InitializeComponent();
systemNameTextBox.Text = System;
contactName1TextBox.Text = Manager;
functionNameTextBox.Text = Function;
durationMSTextBox.Text = Speed;
}
}
Have you tried with:
gridEXMon.DataSource = dsOut.Tables[0];
// next line is not required if you've already defined proper grid structure
gridEXMon.RetrieveStructure();
Janus has also his own forum available here. You can find there a lot of useful information. For browsing I will use IE. Janus forum works good only with IE...
Edited:
How ReportInfo class can know what record have you selected? Especially that you have fallowing code:
DataTable dt = dsOut.Tables["Table"];
DataRow dr = dt.Rows[0]; // always first record is taken!
Probably you should define ctor with row index:
public ReportInfo(int rowIndex)
{
...
DataTable dt = dsOut.Tables["Table"];
DataRow dr = dt.Rows[rowIndex];
....
}

Read/Load xml file by form loading using c#

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.

print dynamically generated checkbox selected rows from datagridview to crystal report on another form c#

I have dynamically added checkboxes for each row in datagridview (form1)and i am trying to generate crystal report on a new form (form 2) for only those rows whose checkbox is checked.
My code on form1 button click is
private void btn_Print_Click(object sender, EventArgs e)
{
//im trying to insert selected rows in datatable which is datasource for crystal report
DataTable table = new DataTable();
int i = 1;
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
//dataGridView1.SelectedRows[0].Cells["select"].Value)
{
for (int j = 1; j < dataGridView1.ColumnCount; ++j)
{
table.Rows[i][j] = row.Cells[j].Value;
}
++i;
}
if (cb_reptype.SelectedItem.ToString() == "Individual")
{
//here im specifying the path for new form2
string path = table.ToString();//dataGridView1.SelectedRows[1].Cells["table"].Value.ToString();
Form2 f2 = new Form2(path);
//ReportDocument crystal = new ReportDocument();
//crystal.Load(dataGridView1.SelectedRows[0].Cells["ReportPath"].Value.ToString());
//pass = crystal;
f2.Show();
}
and my code on form2 is
public partial class Form2 : Form
{
public string source;
public Form2(string path)
{
source = path;
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
this.crystalReportViewer1.ReportSource = source;
}
}
on debugging the program and button click event , new form is opening but it is showing below error.
I have tried a lot of research on this topic but not upto the mark.
Kindly reply as soon as possible.. Thanks :)
Try providing valid document in Form constructor inside button click event.
Valid document could be .xml, .rpt file for generating crystal report.
For the current scenario do few additions:
if (cb_reptype.SelectedItem.ToString() == "Individual")
{
DataSet ds = new DataSet();
ds.Tables.Add(table);
ds.WriteXmlSchema("Drive:\\Somefolder\\Sample.xml"); // this generates Xml file.
Now pass this path to Form constructor as this is valid report file.
Form f2 = new Form("Drive:\\Somefolder\\Sample.xml");
f2.show();
}
You need to add rows to DataTable before adding any value from datagrid.
while(table.Rows.Count<dataGridView1.SelectedRows.Count)
{
table.Rows.Add();
}
Once done with this you can add values from datagrid:
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
for (int j = 1; j < dataGridView1.ColumnCount; ++j)
{
table.Rows[i][j] = row.Cells[j].Value;
}
++i;
}
Hope it works.

passing string value fill dropdown from database

I need to fill the dropdown value from database passing string value.here i am gettin filled dataset from database but it is not binding so that i am unable to fill properly the dropdown and select items from dropdown.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string strCreatedId = string.Empty;
strCreatedId = "2";
fillgroupname(id_ddlgroupname,strCreatedId);
}
}
public void fillgroupname(DropDownList id_ddlgroupname, string strCreatedId)
{
DataSet dsgroup = new DataSet();
dsgroup = objUser.GetFillGroup(strCreatedId);
if (dsgroup.Tables.Count > 0)
{
if (dsgroup.Tables[0].Rows.Count > 0)
{
this.id_ddlgroupname.DataSource = dsgroup;
this.id_ddlgroupname.DataTextField = "c_group_name";
this.id_ddlgroupname.DataValueField = "c_group_name";
this.id_ddlgroupname.DataBind();
this.id_ddlgroupname.Items.Insert(0, "--Select--");
}
}
I will upload image as it appears.
Image1:
Image2:
Image3:
like this the dropdown issue i am facing i am not able to know where i am going wrong.pls help me.
Use this code
public void fillgroupname(DropDownList id_ddlgroupname, string strCreatedId)
{
DataSet dsgroup = new DataSet();
dsgroup = objUser.GetFillGroup(strCreatedId);
id_ddlgroupname.DataSource = dsgroup;
id_ddlgroupname.DataTextField = "c_group_name";
id_ddlgroupname.DataValueField = "c_group_name";
id_ddlgroupname.DataBind();
ListItem li = new ListItem("--Select--","0");
id_ddlgroupname.Items.Insert(0, li);
}
This is working for me, I hope it will be use full for you.
sorry. I got solved my issue it was problem in my validation using jquery.

Trying to grab information from a Data Table in Form 2 and set Textboxes in Form 1 using C#

I have two forms (Form 1 and Form 2), I am successful in passing a data table from Form 1 to Form 2 by filling a data grid view in a dialog box. I also have an event handler to capture double click events on a selected row. When the event occurs I want to set textboxes in form 1 from the click event in form 2. No matter what I try I can not seem to show the text inside the textboxes. Below is my code:
//Code begins here
//....Function to fill data table from form 1 and pass to form 2
private void buttonNewEntryLookUp_Click(object sender, EventArgs e)
{
try
{
cs.Open();
da.SelectCommand = new SqlCommand("Select ctx_customername AS Customer, ctx_contactname AS Contact, ctx_custaddress1 AS Address, ctx_custcity AS City, ctx_custstate AS State, nno_custzip AS ZIP, ctx_custemail AS Email FROM Customers WHERE nno_custphone = '" + maskedTextBoxNewLogTel.Text + "'", cs);
dt.Clear();
da.Fill(dt);
}
catch
{
MessageBox.Show("Connection to Database could not be established, please close this application and try again. If problem continues please contact server Admin. Thank you.", "AAMP");
//Display this message if connection could not be made
}
cs.Close();//close connection to db
if (dt.Rows.Count == 0)//if there are no returned results then this must be a new entry into the database
{
MessageBox.Show("Phone Number Not Found in Database.", "AAMP");
}
else//number was found
{
Form2 form2 = new Form2(dt);//create object of form 2 and pass the data table.
form2.ShowDialog();//show form 2 with data table in the grid view.
}
}
public void getContactInfo(string[] contactInfo)
{
textBoxNewLogCustomerName.Text = contactInfo[0];
textBoxNewLogContactName.Text = contactInfo[1];
textBoxNewLogAddress.Text = contactInfo[2];
textBoxNewLogCity.Text = contactInfo[3];
textBoxNewLogState.Text = contactInfo[4];
textBoxNewLogZIP.Text = contactInfo[5];
textBoxNewLogEmail.Text = contactInfo[6];
}
//code for form 2
public partial class Form2 : Form
{
/*Globals for Form 2*/
DataTable g_dt;
public Form2(DataTable dt)
{
InitializeComponent();
dataGridViewLookUp.DataSource = dt;
g_dt = dt;
}
private void dataGridViewLookUp_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
Form1 form1 = new Form1();
string[] contactInfo = new string[7];
contactInfo[0] = Convert.ToString(g_dt.Rows[e.RowIndex]["Customer"]);
contactInfo[1] = Convert.ToString(g_dt.Rows[e.RowIndex]["Contact"]);
contactInfo[2] = Convert.ToString(g_dt.Rows[e.RowIndex]["Address"]);
contactInfo[3] = Convert.ToString(g_dt.Rows[e.RowIndex]["City"]);
contactInfo[4] = Convert.ToString(g_dt.Rows[e.RowIndex]["State"]);
contactInfo[5] = Convert.ToString(g_dt.Rows[e.RowIndex]["ZIP"]);
contactInfo[6] = Convert.ToString(g_dt.Rows[e.RowIndex]["Email"]);
form1.getContactInfo(contactInfo);//return the row number being clicked.
this.Close();
}
}
I am successful in passing the data table to form 2 and capturing the correct information to fill the string array but when I pass the string array back by calling the getContactInfo function I can not seem to set my textboxes with the data. Can someone please, please help!
Thanks.
Your OP is a little vague, but I have some code that does this, takes some data in form 2 and sends it back to form 1.
Here's the code from form1:
private void btnGroupNameLookup_Click(object sender, EventArgs e)
{
//instantiate an instance of the grp name lookup form
frmGroupNameLookup lookupName = new frmGroupNameLookup();
//add an event handler to update THIS form when the lookup
//form is updated. (This is when LookupUpdated fires
lookupName.GroupNamesFound += new frmGroupNameLookup.LookupHandler(lookupName_GroupNamesFound);
//rc.ReconCFUpdated += new ReconCaseFileChecklist.ReconCFListHandler(ReconCFForm_ButtonClicked);
lookupName.Show();
}
void lookupName_GroupNamesFound(object sender, GroupNameLookupUpdateEventArgs e)
{
//update the list boxes here
foreach (string s in e.Parents)
{
lstFilteredGroupParents.Items.Add(s);
}
foreach (string s in e.Groups)
{
lstFilteredGroups.Items.Add(s);
//link supgroups and plan ids
GetFilteredSubgroupNos(s);
GetFilteredPlanIds(s);
}
//ensure dupes are stripped out
//filter out duplicates
var noDupeSubgroups = subgroupList.Distinct().ToList();
noDupeSubgroups.Sort();
foreach (string s in noDupeSubgroups)
{
lstFilteredSubgroups.Items.Add(s);
}
var noDupePlanIDs = planIDList.Distinct().ToList();
noDupePlanIDs.Sort();
foreach (string s in noDupePlanIDs)
{
lstFilteredPlanID.Items.Add(s);
}
}
From Form2
public partial class frmGroupNameLookup : Form
{
//add a delegate, the GroupNameLookupUpdateEventArgs class is defined at the bottom
//of this file
public delegate void LookupHandler(object sender, GroupNameLookupUpdateEventArgs e);
//add an event of the delegate type
public event LookupHandler GroupNamesFound;
//this event closes the forms and passes 2 lists back to form 1
private void btnCommit_Click(object sender, EventArgs e)
{
List<string> prnt = new List<string>();
List<string> grp = new List<string>();
//get selected rows
if (grdLookup.SelectedRows.Count > 0)
{
foreach (DataGridViewRow row in grdLookup.SelectedRows)
{
prnt.Add(row.Cells[0].Value.ToString());
grp.Add(row.Cells[1].Value.ToString());
}
//filter out duplicates
var noDupeParentGroups = prnt.Distinct().ToList();
noDupeParentGroups.Sort();
// instance the event args and pass it each value
GroupNameLookupUpdateEventArgs args =
new GroupNameLookupUpdateEventArgs(noDupeParentGroups, grp);
// raise the event with the updated arguments
this.GroupNamesFound(this, args);
this.Dispose();
}
}
}
public class GroupNameLookupUpdateEventArgs : System.EventArgs
{
// add local member variables to hold text
private List<string> mParents = new List<string>();
private List<string> mGroups = new List<string>();
// class constructor
public GroupNameLookupUpdateEventArgs(List<string> sParents, List<string> sGroups)
{
this.mParents = sParents;
this.mGroups = sGroups;
}
// Properties - Viewable by each listener
public List<string> Parents
{
get { return mParents; }
}
public List<string> Groups
{
get { return mGroups; }
}
}
Simple. Make the contact information a method public in Form2 and then just assign it after the ShowDialog() in form1.
else//number was found
{
Form2 form2 = new Form2(dt);//create object of form 2 and pass the data table.
form2.ShowDialog();//show form 2 with data table in the grid view.
getContactInfo(form2.ContactInfoFromForm2);
}
You're passing the datatable into the constructor of Form2:
Form2 form2 = new Form2(dt);
You could instead pass a reference to the entire Form1:
Form2 form2 = new Form2(this);
Then you make public methods on Form1 that Form2 can use to update data. Something like this:
//In Form1
public DataTable getDataTable(){
//return datatable
}
public void setTextBoxValue(string Value){
//Set the value
}
And then in Form2
private Form1 _form1;
public Form2(Form1 form1){
_form1 = form1;
dataGridViewLookUp.DataSource = _form1.getDataTable();
g_dt = dt;
}
private void dataGridViewLookUp_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
_form1.setTextBoxValue(Convert.ToString(g_dt.Rows[e.RowIndex]["Customer"]));
//etc
}
Are you getting an error or is the data just not displaying. Maybe try a ToString() method behind each stringarray index in the getcontactinfo method. (i.e. contactInfo[0].ToString();)

Categories

Resources