resultgrid and IsfirstrowAsColumnNames
private void Form4_Load(object sender, EventArgs e, object ResultGrid )
{
using (OpenFileDialog dialog = new OpenFileDialog()
{ Filter = "Excel workbook|*xls", ValidateNames = true })
{
if (dialog.ShowDialog()==DialogResult.OK)
{
FileStream fileStream = File.Open(dialog.FileName, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(fileStream);
reader.IsFirstRowAsColumnNames()() = false;
ds = reader.AsDataSet();
ResultGrid.DataSource() = ds.Tables[0];
}
}
}
Related
I'm new in C#, And I have tried many solutions but couldn't do it, this is my code , How to write this four (bytes) declared in first method but I want write them to file in second method.
private void openfiles()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open";
ofd.Filter = "Bin files|*.bin";
if (ofd.ShowDialog() == DialogResult.OK)
{
string path = ofd.FileName;
using (BinaryReader b = new BinaryReader(File.Open(path, FileMode.Open)))
{
long size = new System.IO.FileInfo(path).Length;
long ssize = new System.IO.FileInfo(path).Length / 1024;
int allsize = unchecked((int)size);
byte[] bytes = b.ReadBytes(4);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
using (BinaryWriter bw =new BinaryWriter(File.Open("FileName.bin",FileMode.Create)))
{
bw.Write(bytes);
bw.Close();
}
}
First you need to have somewhere to store the data after it is read and until it is written again. Best guess would be a field in the form, but that is design decision you need to make.
Next split up your code into functional parts, and don't put everything into button handlers. This way parts of the code can be re-used if needed.
Because the design intent is not clear, I have a very basic skeleton code below:
public partial class Form1 : Form
{
string _filename;
byte[] _data;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Title = "Open";
dlg.Filter = "Bin files|*.bin";
if (dlg.ShowDialog() == DialogResult.OK)
{
this._filename = dlg.FileName;
this._data = ReadHeader(_filename);
MessageBox.Show($"Read {_data.Length} bytes from {_filename}");
}
}
private void button2_Click(object sender, EventArgs e)
{
string destination = "Filename.bin";
if (MessageBox.Show($"About to overwrite {destination} with data from {_filename}. Proceed?", "File Header", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
WriteHeader(destination, this._data);
}
}
static byte[] ReadHeader(string filename)
{
byte[] fileHeader;
var fs = File.OpenRead(filename);
using (var fr = new BinaryReader(fs))
{
fileHeader = fr.ReadBytes(4);
}
fs.Close();
return fileHeader;
}
static void WriteHeader(string filename, byte[] fileHeader)
{
var fs = File.OpenWrite(filename);
using (var fw = new BinaryWriter(fs))
{
fw.Write(fileHeader);
}
fs.Close();
}
}
Im trying to export data from gridview to .csv and saving it using save file dialog, but when i press the button, nothing happens. Gridview works correctly, here is the code:
public struct DataParameters
{
public List<Currency> currency;
public string Filename;
}
public static DataParameters dataParameters;
On button click - open file dialog export file to csv and save it
protected void Button1_Click(object sender, EventArgs e)
{
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "CSV
files (*.csv)|*.csv|All files (*.*)|*.*" ,
ValidateNames = true, InitialDirectory = #"C:\",
RestoreDirectory = true, CheckFileExists = true, CheckPathExists
= true, DefaultExt = "csv" }) {
if (sfd.ShowDialog() == DialogResult.OK)
{
dataParameters.currency = GridView1.DataSource as
List<Currency>;
dataParameters.Filename = sfd.FileName;
}
}
List<Currency> currencies = dataParameters.currency;
string filename = dataParameters.Filename;
using (StreamWriter sw = new StreamWriter(new FileStream(filename,
FileMode.Create), Encoding.UTF8))
{
StringBuilder sb = new StringBuilder();
foreach (Currency c in currencies)
{
sb.AppendLine(string.Format($"{c.Drzava} {c.Sifra_valute} {
{c.Valuta} {c.Jedinica} {c.Kupovni_tecaj} {c.Srednji_tecaj}
{c.Prodajni_tecaj}"));
}
sw.Write(sb.ToString());
}
}
Nothing happens when i press the button
I am trying to add a feature into my application where users can choose the sheets from the comboBox. But I am hitting some bumps, I need some help! I was able to read the the excel file previously as I already sheet the default sheetname. But now I am able to get the sheetname into my comboBox, but I can't seem to read the excel file now? Please help me
public static DataTable ExcelToDataTable (string fileName)
{
using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
UseColumnDataType = true,
ConfigureDataTable = (data) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true
}
});
DataTableCollection table = result.Tables;
DataTable resultTable = table["Sheet1"];
return resultTable;
}
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel 2003 Worksheet|*.xls|Excel 2007 Worksheet|*.xlsx", ValidateNames = true, Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
dataGridView1.DataSource = ExcelToDataTable(ofd.FileName);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And Now
public static DataSet ExcelToDataTable (string fileName)
{
using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
UseColumnDataType = true,
ConfigureDataTable = (data) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true
}
});
return result;
}
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel 2003 Worksheet|*.xls|Excel 2007 Worksheet|*.xlsx", ValidateNames = true, Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
comboBox1.Items.Clear();
foreach (DataTable dt in ExcelToDataTable(ofd.FileName).Tables)
{
comboBox1.Items.Add(dt.TableName);
}
DataTableCollection table = ExcelToDataTable(ofd.FileName).Tables;
DataTable resultTable = ExcelToDataTable(ofd.FileName).Tables[comboBox1.SelectedIndex];
dataGridView1.DataSource = resultTable
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
May I know what went wrong? I am getting an error of Cannot find table -1 but I can see the sheetname in the excel just not the content
At first use a DataSet property in your form:
private DataSet ExcelDateSet { get; set; }
And add a method to read a table from it like this:
private DataTable GetExcelDataTable(string sheetName)
{
if (string.IsNullOrEmpty(sheetName) || !ExcelDateSet.Tables.Contains(sheetName))
{
// Notify user to select a sheet-name from your ComboBox!
// or you can return first-sheet info as default like this:
// return ExcelDateSet.Tables[0];
}
return ExcelDateSet.Tables[sheetName];
}
then set its value in your btnOpen_Click like this:
ExcelDataSet = ExcelToDataTable(ofd.FileName);
dataGridView1.DataSource = GetExcelDataTable(comboBox1.SelectedText);
dataGridView1.DataBind();
I have a Link in Richtextbox and it works good but if I save that Richtextbox in to database and then load it that link to be deleted and I just can see the text of that Link
for example my Richtextbox have bottom text:
This is a link
But after save and load again I just can see the text:
This is a link
The hyperlink created dynamically from selected text as bellow:
RichTextBox.IsDocumentEnabled = true;
RichTextBox.IsReadOnly = true;
Run run = new Run(RichTextBox.Selection.Text);
Hyperlink hyp = new Hyperlink(run) { TargetName = run.Text };
TERM.WordMain main = new TERM.WordMain();
hyp.Click += new RoutedEventHandler(main.hyperLink_Click);
hyp.NavigateUri = new Uri("http://search.msn.com");
RichTextBox.Cut();
var container = new InlineUIContainer(new TextBlock(hyp), RichTextBox.Selection.Start);
RichTextBox.IsDocumentEnabled = true;
RichTextBox.IsReadOnly = false;
Saving richtextbox content as RTF format to text field:
public static string ToStringFromBytes(System.Windows.Controls.RichTextBox richTextBox)
{
if (richTextBox.Document.Blocks.Count == 0)
{
return null;
}
MemoryStream memoryStream = new MemoryStream();
TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
textRange.Save(memoryStream, System.Windows.DataFormats.Rtf);
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
And load from database to flowdocument
public static FlowDocument LoadFromString(string s)
{
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(s);
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(s));
FlowDocument doc = new FlowDocument();
TextRange textRange = new TextRange(doc.ContentStart, doc.ContentEnd);
textRange.Load(stream, System.Windows.DataFormats.Rtf);
return doc;
}
catch (Exception ex)
{
throw;
}
}
The following sample seems to do the trick.
Here I load and save the XAML instead of the text in rtf format. Note also that you need to add handlers for the hyperlinks back to the elements after loading, since they will not be serialized.
public partial class MainWindow : Window
{
private const string _stateFile = "state.xaml";
public MainWindow()
{
InitializeComponent();
richTextBox.IsReadOnly = false;
}
private void createLinkButton_Click(object sender, RoutedEventArgs e)
{
richTextBox.IsDocumentEnabled = false;
richTextBox.IsReadOnly = true;
var textRange = richTextBox.Selection;
var hyperlink = new Hyperlink(textRange.Start, textRange.End);
hyperlink.TargetName = "value";
hyperlink.NavigateUri = new Uri("http://search.msn.com");
hyperlink.RequestNavigate += HyperlinkOnRequestNavigate;
richTextBox.IsDocumentEnabled = true;
richTextBox.IsReadOnly = false;
}
private void HyperlinkOnRequestNavigate(object sender,
RequestNavigateEventArgs args)
{
// Outputs: "Requesting: http://search.msn.com, target=value"
Console.WriteLine("Requesting: {0}, target={1}", args.Uri, args.Target);
}
private void SaveXamlPackage(string filePath)
{
var range = new TextRange(richTextBox.Document.ContentStart,
richTextBox.Document.ContentEnd);
var fStream = new FileStream(filePath, FileMode.Create);
range.Save(fStream, DataFormats.XamlPackage);
fStream.Close();
}
void LoadXamlPackage(string filePath)
{
if (File.Exists(filePath))
{
var range = new TextRange(richTextBox.Document.ContentStart,
richTextBox.Document.ContentEnd);
var fStream = new FileStream(filePath, FileMode.OpenOrCreate);
range.Load(fStream, DataFormats.XamlPackage);
fStream.Close();
}
// Reapply event handling to hyperlinks after loading, since these are not saved:
foreach (var paragraph in richTextBox.Document.Blocks.OfType<Paragraph>())
{
foreach (var hyperlink in paragraph.Inlines.OfType<Hyperlink>())
{
hyperlink.RequestNavigate += HyperlinkOnRequestNavigate;
}
}
}
private void saveButton_Click(object sender, RoutedEventArgs e)
{
SaveXamlPackage(_stateFile);
}
private void loadButton_Click(object sender, RoutedEventArgs e)
{
LoadXamlPackage(_stateFile);
}
}
I'm working on an assignment and I'm trying to either convert an image to base64 but after trying some examples on here I get an error message saying the bytes can't exceed infinity, and someone in class suggested I should export the image path instead.
below is the code I have to open the image
private void button1_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "PNG Files (.png)|*.png|JPEG Files (.jpg)|*.jpg";
openFileDialog1.FilterIndex = 2;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Bitmap loadedImage = new Bitmap(openFileDialog1.FileName);
setImage.Size = loadedImage.Size;
setImage.BackgroundImage = loadedImage;
imageWidth.Text = loadedImage.Size.Width.ToString();
imageHeight.Text = loadedImage.Size.Height.ToString();
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
after opening the Image I need to be able to export the dimensions of the image to XML but I also want to export the image path there as well.
Below is the code I'm using to export as you can see I haven't done the image export as I'm unsure what to do there
private void exportButton_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
DataTable xyPos = new DataTable();
xyPos.TableName = "Position";
xyPos.Columns.Add("X");
xyPos.Columns.Add("Y");
ds.Tables.Add(xyPos);
DataTable whDimen = new DataTable();
whDimen.TableName = "Dimensions";
whDimen.Columns.Add("Width");
whDimen.Columns.Add("Height");
ds.Tables.Add(whDimen);
DataTable loadImage = new DataTable();
loadImage.TableName = "LoadedImage";
loadImage.Columns.Add("Image");
ds.Tables.Add(loadImage);
DataRow posRow = ds.Tables["Position"].NewRow();
posRow["X"] = Xcoord.Text;
posRow["Y"] = Ycoord.Text;
ds.Tables["Position"].Rows.Add(posRow);
DataRow dimenRow = ds.Tables["Dimensions"].NewRow();
dimenRow["Width"] = imageWidth.Text;
dimenRow["Height"] = imageHeight.Text;
ds.Tables["Dimensions"].Rows.Add(dimenRow);
//Export Image
DataRow imageRow = ds.Tables["LoadedImage"].NewRow();
imageRow["Image"] = setImage.BackgroundImage;
//ImageConverter imgConvert = new ImageConverter();
//byte[] imgByte = (byte[])imgConvert.ConvertTo(imageRow["Image"], typeof(byte[]));
//Convert.ToBase64String(imgByte);
//Convert.ToBase64String((byte[])imageRow["Image"]);
ds.Tables["LoadedImage"].Rows.Add(imageArray);
ds.WriteXml("XMLFile1.xml");
}