Show XML data in datagrid - c#

I am doing a weather API project. The upcoming 7 days weather information is displaying successfully in message boxes.
Instead of message boxes, how can display all the data with a datagridview?
This is my current working code:
string uri = string.Format("http://api.apixu.com/v1/forecast.xml?key=keygoeshere&q={0}&days=7", city);
XDocument doc = XDocument.Load(uri);
foreach (var npc in doc.Descendants("forecastday"))
{
MessageBox.Show((string)npc.Descendants("date").FirstOrDefault());
MessageBox.Show("Max temp " + (string)npc.Descendants("maxtemp_c").FirstOrDefault());
MessageBox.Show("Min temp " + (string)npc.Descendants("mintemp_c").FirstOrDefault());
MessageBox.Show("Text " + (string)npc.Descendants("text").FirstOrDefault());
MessageBox.Show("Icon " + (string)npc.Descendants("http"+"icon").FirstOrDefault());
}

Put data into a DataTable and then make the DataTable the DataSource of the DGV.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.IO;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add("Date", typeof(string));
dt.Columns.Add("Max Temp", typeof(string));
dt.Columns.Add("Min Temp", typeof(string));
dt.Columns.Add("Text", typeof(string));
dt.Columns.Add("Icon", typeof(Bitmap));
string city = "London";
string uri = string.Format("http://api.apixu.com/v1/forecast.xml?key=keygoeshere&q={0}&days=7", city);
XDocument doc = XDocument.Load(uri);
foreach (var npc in doc.Descendants("forecastday"))
{
string iconUri = (string)npc.Descendants("icon").FirstOrDefault();
WebClient client = new WebClient();
byte[] image = client.DownloadData("http:" + iconUri);
MemoryStream stream = new MemoryStream(image);
Bitmap newBitMap = new Bitmap(stream);
dt.Rows.Add(new object[] {
(string)npc.Descendants("date").FirstOrDefault(),
(string)npc.Descendants("maxtemp_c").FirstOrDefault(),
(string)npc.Descendants("mintemp_c").FirstOrDefault(),
(string)npc.Descendants("text").FirstOrDefault(),
newBitMap
});
}
dataGridView1.DataSource = dt;
}
}
}

Related

how can i convert xml document to data table in c#

i am getting the following response from api as xml
<ROOT>
<valid>1</valid>
<org_name> test org </org_name>
<count_of_vedios>3</count_of_vedios>
<total_length>351</total_length>
<Video1>
<Title>The Distinguished Gentleman</Title>
<Director>Jonathan Lynn</Director>
<Length>112 Minutes</Length>
<Format>DVD</Format>
<Rating>R</Rating>
</Video1>
<Video2>
<Title>Her Alibi</Title>
<Director>Bruce Beresford</Director>
<Length>94 Mins</Length>
<Format>DVD</Format>
<Rating>PG-13</Rating>
</Video2>
<Video3>
<Title>Chalte Chalte</Title>
<Director>Aziz Mirza</Director>
<Length>145 Mins</Length>
<Format>DVD</Format>
<Rating>N/R</Rating>
</Video3>
</ROOT>
i need to fill some fields of aspx page with the information :
org_name : test org
count_of_vedios : 3
total_length : 351
also i need to fill gridview with the vedios that is in nodes
Title | Director | Length | Format | Rating |
dataset will have 4 tables here , so what i did is replace the vedio# tage with vedio , now the dataset will have 2 tables one for the general nodes and the another for vedios
DataTable general_dt = new DataTable();
DataTable vedios_dt = new DataTable();
string xml_str = document.DocumentElement.InnerXml.ToString();
xml_str = Regex.Replace(xml_str, #"<Video[0-9]{1,3}>", "<Video>");
xml_str = Regex.Replace(xml_str, #"<\/Video[0-9]{1,3}>", "</Video>");
DataSet ds = new DataSet();
ds.ReadXml(new System.IO.StringReader(xml_str));
if (ds.Tables.Count > 0)
{
XmlNode newnode;
newnode = document.ReadNode(new XmlTextReader(new StringReader(xml_str)));
if (newnode["valid"].InnerText.ToString() == "1")
{
general_dt = ds.Tables[0];
vedios_dt = ds.Tables[1];
}
}````
Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Directory", typeof(string));
dt.Columns.Add("Length", typeof(string));
dt.Columns.Add("Format", typeof(string));
dt.Columns.Add("Rating", typeof(string));
XDocument doc = XDocument.Load(FILENAME);
List<XElement> videos = doc.Root.Elements().Where(x => x.Name.LocalName.StartsWith("Video")).ToList();
foreach (XElement video in videos)
{
dt.Rows.Add(new object[] {
(string)video.Element("Title"),
(string)video.Element("Director"),
(string)video.Element("Length"),
(string)video.Element("Format"),
(string)video.Element("Rating")
});
}
}
}
}

Removing a row from a csv file when it is selected from a comboBox and a button pressed

I recently asked about a piece of code to hold data for my trading cards. I have a file that contains the overall list of the cards in a CSV file. I was wondering if there was any way to remove a row from the CSV file when the card number is selected and the submit button pressed. The code I currently have is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace YuGiOh_Card_List
{
public partial class frmAddLOB : Form
{
List<string> cardNo = new List<string>();
List<string> cardName = new List<string>();
List<string> cardRarity = new List<string>();
List<string> cardType = new List<string>();
public frmAddLOB()
{
InitializeComponent();
StreamReader reader = File.OpenText("..\\Debug\\lobList.csv");
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
cardNo.Add(values[0]);
cardName.Add(values[1]);
cardRarity.Add(values[2]);
cardType.Add(values[3]);
cboCardNo.Items.Add(values[0]);
}
reader.Close();
}
private void cboCardNo_SelectedIndexChanged(object sender, EventArgs e)
{
lblCardNoFinal.Text = cardNo[cboCardNo.SelectedIndex];
lblCardNameFinal.Text = cardName[cboCardNo.SelectedIndex];
lblCardRarityFinal.Text = cardRarity[cboCardNo.SelectedIndex];
lblCardTypeFinal.Text = cardType[cboCardNo.SelectedIndex];
}
private void btnAdd_Click(object sender, EventArgs e)
{
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text);
Global.card.Add(card);
File.AppendAllLines(file, new[] { card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter + card.CardType });
MessageBox.Show("Card Added");
}
}
}
So I want the row to be removed from the 'loblist.csv' and added to the LOB file (which it is currently doing). Thanks
This should work (untested). Unfortunately, there's no classes/methods available in .Net (AFAIK) for in-place editing of text files (it makes sense when you think about it I guess). Disclaimer - there are much cleaner ways to do what you're aiming for here functionality-wise, including the approach described by Plutonix above:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace YuGiOh_Card_List
{
public partial class frmAddLOB : Form
{
List<string> cardNo = new List<string>();
List<string> cardName = new List<string>();
List<string> cardRarity = new List<string>();
List<string> cardType = new List<string>();
List<string> Lines = new List<string>();
public frmAddLOB()
{
InitializeComponent();
StreamReader reader = File.OpenText("..\\Debug\\lobList.csv");
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
Lines.Add(line);
cardNo.Add(values[0]);
cardName.Add(values[1]);
cardRarity.Add(values[2]);
cardType.Add(values[3]);
cboCardNo.Items.Add(values[0]);
}
reader.Close();
}
private void cboCardNo_SelectedIndexChanged(object sender, EventArgs e)
{
lblCardNoFinal.Text = cardNo[cboCardNo.SelectedIndex];
lblCardNameFinal.Text = cardName[cboCardNo.SelectedIndex];
lblCardRarityFinal.Text = cardRarity[cboCardNo.SelectedIndex];
lblCardTypeFinal.Text = cardType[cboCardNo.SelectedIndex];
}
private void btnAdd_Click(object sender, EventArgs e)
{
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text,
lblCardTypeFinal.Text);
Global.card.Add(card);
var newLine = card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter +
card.CardType;
File.AppendAllLines(file,
new string [] {newLine});
if (Lines.Contains(newLine))
{
Lines.Remove(newLine);
File.WriteAllLines("..\\Debug\\lobList.csv", Lines);
}
MessageBox.Show("Card Added");
}
}
}

how to extract column of data using regular expression

i am trying to write c# code to extract columns of data. my data looks like
what should be the regular expression if i want to extract "everything" "under" a column header for example "COMMAND" or "PID".
No need to use regular expression. String Split method will work. Try code like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
namespace ConsoleApplication53
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("PID", typeof(int));
dt.Columns.Add("TT", typeof(string));
dt.Columns.Add("STAT", typeof(string));
dt.Columns.Add("TIME", typeof(DateTime));
dt.Columns.Add("COMMAND", typeof(string));
StreamReader reader = new StreamReader(FILENAME);
int lineCount = 0;
string inputLine = "";
while ((inputLine = reader.ReadLine) != null)
{
if (++lineCount > 2)
{
string[] inputArray = inputLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
dt.Rows.Add(new object[] {
int.Parse(inputArray[0]),
inputArray[1],
inputArray[2],
DateTime.Parse(inputArray[3]),
inputArray[4]
});
}
}
}
}
}

Reading XML dynamic data in SQL Server

I have a XML column in a table contains a collection of data. Every record may hold a different collection type like sometimes customers data and sometimes invoices data etc.
How can I read that cell & convert it to a table in order to bind it to a data grid, so the collection some times looks like that
<ArrayOfReceiptTransfer_Receipt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ReceiptTransfer_Receipt>
<ReceiptTransfer_Receipt_ID>77491</ReceiptTransfer_Receipt_ID>
<ReceiptTransferID>17839</ReceiptTransferID>
<ReceiptID>74080</ReceiptID>
<Amount>500.00</Amount>
</ReceiptTransfer_Receipt>
</ArrayOfReceiptTransfer_Receipt>
And sometimes looks like
<ArrayOfInvoiceBudgetItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<InvoiceBudgetItem>
<InvoiceID>21978</InvoiceID>
<BudgetItemID>1473</BudgetItemID>
<Amount>12</Amount>
</InvoiceBudgetItem>
<InvoiceBudgetItem>
<InvoiceID>21978</InvoiceID>
<BudgetItemID>1475</BudgetItemID>
<Amount>11</Amount>
</InvoiceBudgetItem>
</ArrayOfInvoiceBudgetItem>
You already have one root tag so this will also work
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string input =
"<ArrayOfReceiptTransfer_Receipt xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<ReceiptTransfer_Receipt>" +
"<ReceiptTransfer_Receipt_ID>77491</ReceiptTransfer_Receipt_ID>" +
"<ReceiptTransferID>17839</ReceiptTransferID>" +
"<ReceiptID>74080</ReceiptID>" +
"<Amount>500.00</Amount>" +
"</ReceiptTransfer_Receipt>" +
"</ArrayOfReceiptTransfer_Receipt>";
string xml = string.Format("<?xml version=\"1.0\" encoding=\"utf-8\"?>{0}", input);
StringReader reader = new StringReader(xml);
DataSet ds = new DataSet();
ds.ReadXml(reader);
dataGridView1.DataSource = ds.Tables[0];
}
}
}
​
Try this
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string input =
"<ArrayOfReceiptTransfer_Receipt xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
"<ReceiptTransfer_Receipt>" +
"<ReceiptTransfer_Receipt_ID>77491</ReceiptTransfer_Receipt_ID>" +
"<ReceiptTransferID>17839</ReceiptTransferID>" +
"<ReceiptID>74080</ReceiptID>" +
"<Amount>500.00</Amount>" +
"</ReceiptTransfer_Receipt>" +
"</ArrayOfReceiptTransfer_Receipt>";
string xml = string.Format("<?xml version=\"1.0\" encoding=\"utf-8\"?><root>{0}</root>", input);
StringReader reader = new StringReader(xml);
DataSet ds = new DataSet();
ds.ReadXml(reader);
dataGridView1.DataSource = ds.Tables[1];
}
}
}
​

c# Oledb excel to txt, how to also recognize letters?

I have an application which uses open file dialog to open an excel file and then convert it to .txt and it works fine, almost. Currently it can only read tables with only numbers in them but I need to add a function so that it could also read letters. What should I change to make it able to read letters/words as well as numbers?
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
}
private void BtnFileOpen_Click(object sender, RoutedEventArgs e)
{
var fileDialog = new System.Windows.Forms.OpenFileDialog();
var result = fileDialog.ShowDialog();
switch (result)
{
case System.Windows.Forms.DialogResult.OK:
var file = fileDialog.FileName;
TxtFile.Text = file;
TxtFile.ToolTip = file;
break;
case System.Windows.Forms.DialogResult.Cancel:
default:
TxtFile.Text = null;
TxtFile.ToolTip = null;
break;
}
}
public void convert_Click(object sender, RoutedEventArgs e)
{
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
exportExcelToTxt(TxtFile.Text, filename);
}
}
static void exportExcelToTxt(string excelFilePath, string outputTxtPath)
{
Dictionary<string, List<long>> values = new Dictionary<string, List<long>>();
using (OleDbConnection excelConnection = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 XML;HDR=YES\"", excelFilePath)))
{
excelConnection.Open();
string firstSheet = getFirstSheetName(excelConnection);
using (OleDbCommand cmd = excelConnection.CreateCommand())
{
cmd.CommandText = string.Format("SELECT * FROM [{0}]", firstSheet);
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt); // Getting all the data in the sheet
foreach (DataRow item in dt.Rows)
{
List<long> toAdd = new List<long>();
string key = item[0] as string;
for (int i = 1; i < dt.Columns.Count; i++)
{
toAdd.Add(Convert.ToInt64(item[i]));
}
values.Add(key, toAdd); // Associating all the "numbers" to the "Name"
}
}
}
}
}
StringBuilder toWriteToTxt = new StringBuilder();
foreach (KeyValuePair<string, List<long>> item in values)
{
// Formatting the output
toWriteToTxt.Append(string.Format("{0}:", item.Key));
foreach (long val in item.Value.Distinct())
{
toWriteToTxt.AppendFormat("\t{0} * {1}\r\n", item.Value.Where(f => f == val).Count(), // Amount of occurrencies of each number
val);
}
}
// Writing the TXT
using (FileStream fs = new FileStream(outputTxtPath, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(toWriteToTxt.ToString());
}
}
}
static string getFirstSheetName(OleDbConnection excelConnection)
{
using (DataTable ExcelTables = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" }))
{
return ExcelTables.Rows[0]["TABLE_NAME"].ToString();
}
}
}
}
You should not convert the values to long in this line:
toAdd.Add(Convert.ToInt64(item[i]));
Also replace all List<long> with List<string>, this should cover pretty much the issue.

Categories