bind a list variable to text box - c#

i have a new question. i have a code to load a list from binary file, i think i did it right but i need to make each variable show in its own text box. this is the ting i cannot find out how to do. can anyone help me or point me to where i can find the information?
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;
using System.Runtime.Serialization.Formatters.Binary;
namespace test
{
public partial class Form1 : Form
{
[Serializable]
public class ore
{
public float Titan;
public float Eperton;
}
ore b1 = null;
ore b2 = null;
public Form1()
{
InitializeComponent();
b2 = new ore();
b1 = new ore();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
float tempFloat;
if (float.TryParse(textBox1.Text, out tempFloat))
{
b1.Titan = tempFloat;
}
else
MessageBox.Show("uh oh");
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
float tempFloat;
if (float.TryParse(textBox1.Text, out tempFloat))
{
b2.Eperton = tempFloat;
}
else
MessageBox.Show("uh oh");
}
private void button1_Click(object sender, EventArgs e)
{
List<ore> oreData = new List<ore>();
oreData.Add(b1);
oreData.Add(b2);
FileStream fs = new FileStream("ore.dat", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, oreData);
fs.Close();
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
List<ore> books = new List<ore>();
private void button2_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream("ore.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
List<ore> books = (List<ore>)bf.Deserialize(fs);
fs.Close();
if (books.Count > 1)
{
textBox3.Text = books[0];//update the first text
textBox4.Text = books[1];//update the second text
}
}
}
}

Windows Forms:
1- Define your List books at class level so you can use it in another methods if needed..
2-
public clas MyForm : Form
{
List<ore> books = new List<ore>();//define at the class scope
private void button2_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream("ore.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
books = (List<ore>)bf.Deserialize(fs);
fs.Close();
if (books.Count > 1)
{
textBox3.Text = books[0];//update the first text
textBox4.Text = books[1];//update the second text
}
}
}
If you need collection of list boxes to be added and removed whenever a book list changes then this is another story... write a comment or update your question...

One solution is to use ListView control instead of a bunch of Textboxs. In the template of Listview, put Textbox control and bind it to your List object.
Alternatively, create Textbox control on the fly.
for(int i=1; i<=books.Count; i++)
{
var textBoxCtrl = new TextBox()
textBoxCtrl.ID = "TextBox"+i.toString();
textBoxCtrl.Text = books[i];
Page.Controls.Add(textBoxCtrl);
}

In ASP.NET:
You can use the ASP.NET FormView object to create your form and then bind the dataset to the form and call the DataBind.
<asp:FormView runat="server" ID="form1">
<ItemTemplate>
<asp:TextBox Text='<%# Bind("") %>'></asp:TextBox>
</ItemTemplate>
</asp:FormView>

Related

No webcam picture with AForge in C#

I am just learning C# and I was trying to implement a webcam picture capture program. I'm using the Aforge library, the thing is that my picturebox is not displaying the webcam image and I don't understand why. If anyone knows my error, please let me know. Thank you in advance.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DarrenLee.Media;
namespace test4
{
public partial class MainForm : Form
{
int count = 0;
Camera myCamera = new Camera();
public MainForm()
{
InitializeComponent();
GetInfo();
myCamera.OnFrameArrived += myCamera_OnFrameArrived;
}
private void GetInfo()
{
var cameraDevices = myCamera.GetCameraSources();
var cameraResolutions = myCamera.GetSupportedResolutions();
foreach (var d in cameraDevices)
cmbCameraDevices.Items.Add(d);
foreach (var r in cameraResolutions)
cmbCameraResolutions.Items.Add(r);
cmbCameraDevices.SelectedIndex = 0;
cmbCameraDevices.SelectedIndex = 0;
}
private void myCamera_OnFrameArrived(object source, FrameArrivedEventArgs e)
{
Image img = e.GetFrame();
picCamera.Image = img;
}
void ComboBox1SelectedIndexChanged(object sender, EventArgs e)
{
myCamera.ChangeCamera(cmbCameraDevices.SelectedIndex);
}
void ComboBox2SelectedIndexChanged(object sender, EventArgs e)
{
myCamera.Start(cmbCameraDevices.SelectedIndex);
}
void Form1FormClosing(object sender, FormClosingEventArgs e)
{
myCamera.Stop();
}
void BTTsaveClick(object sender, EventArgs e)
{
string filename = Application.StartupPath + #"\" + "Image" + count.ToString();
myCamera.Capture(filename);
count++;
}
}
}
Picture of how it looks when I compile it:
https://i.gyazo.com/6956a07405cd4bf5e74c20bc321bd32e.png
I am connecting the picture box with the content in this line:
Image img = e.GetFrame();
picCamera.Image = img;
Make sure you click on the object before writing the code.
Example: Click on the button in the design form then paste the code for BTTsaveClick in the newly created method after clicking on the button.
If you are using Visual Studio, you can check if the methods are referenced. If it's not referenced, that means the code won't be read.

How To Save Background Image On Form Close In C#

I am making a desktop app in c# in which when the user selects specific name of background from the menu strip, then the background shall turn to that required background. The problem is that i cannot save the user input, i tried settings but i cannot find "system.drawing.image" in settings so is there any way i can save the user changed background ? No external backgrounds a user is allowed to change, just the ones in the resource folder. Here is my code which shows error that system.drawing.color cannot take place of drawing.image.
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;
namespace TAC
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
panel1.Location = new Point(165, 157);
panel2.Location = new Point(289, 158);
panel3.Location = new Point(47, 275);
panel4.Location = new Point(47, 402);
this.BackgroundImage = Properties.Settings.Default.FormImage;
}
private void bLUEToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex1;
}
private void gREENToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex2;
}
private void oRANGEToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex3;
}
private void rEDToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex4;
}
private void pURPLEToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex5;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.FormImage = this.BackgroundImage;
}
}
}
Use Save method to save settings
Properties.Settings.Default.Save();
If you want add an image to settings :
Add new setting with type string and use like this:
Save an image to setting ( when you close form)
MemoryStream ms = new MemoryStream();
Propertis.Resources.MyImage.Save(ms,ImageFormat.Jpeg);
Properties.Settings.Default.BackImg = Convert.ToBase64String(ms.ToArray());
Properties.Settings.Default.Save();
And read image from setting and set to background(in form load)
string img = Properties.Settings.Default.BackImg ;
byte[] i = Convert.FromBase64String(img);
this.BackgroundImage = Image.FromStream(new MemoryStream(i));
How add custom settings ?
http://www.codeproject.com/Articles/29130/Windows-Forms-Creating-and-Persisting-Custom-User

How can i print a listbox list in c# windows form app?

I'm currently having issues with my code in terms of getting a printing option to show up when thy click a specific button.
I am making a reminder program and was just experimenting. Also would like to know the most efficient way to add a daily notification system to my program
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.Net.Mail;
using System.IO;
using System.Drawing.Printing;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
namespace simpleapp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add("Reminder: " + textBox1.Text);
}
private void input_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
listBox1.Items.Add("Reminder: " + textBox1.Text );
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int rmd = listBox1.SelectedIndices.Count - 1; rmd >= 0; rmd--)
{
listBox1.Items.RemoveAt(listBox1.SelectedIndices[rmd]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.SelectionMode = SelectionMode.MultiExtended;
}
private void button6_Click(object sender, EventArgs e)
{
FAQ faqs = new FAQ();
faqs.Show();
}
// When the Button is Clicked the List is saved in a ".txt file format for the user to view later
private void button3_Click(object sender, EventArgs e)
{
var Savingfileas = new SaveFileDialog();
Savingfileas.Filter = "Text (*.txt)|*.txt ";
if (Savingfileas.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (var Reminder = new StreamWriter(Savingfileas.FileName, false))
foreach (var item in listBox1.Items)
Reminder.Write(item.ToString() + Environment.NewLine);
MessageBox.Show("File has been successfully saved"+ '\n' + "Thank you for using the Remindr program");
}
}
private void button4_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
Email_Client emc = new Email_Client();
emc.Show();
}
}
}
You have a few options. One is to graphically layout a print document and iterate through your listbox while drawing the text in the textbox using x and y coordinates. A better way would be to get your listbox items into a dataset and use it to generate a report. Are you storing these items in a database for retrieval? Here's a link that should help you get started. The tutorial is in VB.Net but there's only a small amount of code to this and should be easy to repeat using C# code.
Here is an absolutely minimal example of printing a ListBox.
It assumes your ListBox contains strings and shows a PrintPreviewDialog; it sets the page unit to mm, do pick a unit you are comfortable with..!
Of course you may chose one or more different fonts etc..
private PrintDocument document = new PrintDocument();
private void printButton_Click(object sender, EventArgs e)
{
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document = document;
ppd.Document.DocumentName = "TESTING";
document.PrintPage += document_PrintPage;
ppd.ShowDialog();
}
void document_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
int leading = 5;
int leftMargin = 25;
int topMargin = 10;
// a few simple formatting options..
StringFormat FmtRight = new StringFormat() { Alignment = StringAlignment.Far};
StringFormat FmtLeft = new StringFormat() { Alignment = StringAlignment.Near};
StringFormat FmtCenter = new StringFormat() { Alignment = StringAlignment.Near};
StringFormat fmt = FmtRight;
using (Font font = new Font( "Arial Narrow", 12f))
{
SizeF sz = e.Graphics.MeasureString("_|", Font);
float h = sz.Height + leading;
for (int i = 0; i < listBox1.Items.Count; i++)
e.Graphics.DrawString(listBox1.Items[i].ToString(), font , Brushes.Black,
leftMargin, topMargin + h * i, fmt);
}
}
The actual printing is triggered when the user clicks the printer symbol in the dialog.
Note that there are more StringFormat options!

Trying to REopen Sytem.IO Objects

I am making a program that allows you to roll five different types of multi sided "dice", and when you roll a number I want it to store it in a text file. There is a menu strip item at the top of my form that you click, it closes the StreamWriter and FileStream and opens a second form showing what numbers were rolled and by what die they were rolled ( I'm having it be just the numbers rolled now for simplicity's sake) and it displays fine. But when I close the Reader, Stream, and second form and go back to the first form, I try to Reopen the Writer and Stream and it tells me that is already in use.
My First Form's Code:
using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Random ran = new Random();
static FileStream outFile = new FileStream(#"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(outFile);
private int ranNum;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 21);
Display();
}
private void button2_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 13);
Display();
}
private void button3_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 5);
Display();
}
private void button4_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 9);
Display();
}
private void button5_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 11);
Display();
}
private void Display()
{
lblNum.Text = String.Format("{0}", ranNum);
lblNum.Visible = true;
writer.WriteLine(ranNum);
}
private void historyToolStripMenuItem_Click(object sender, EventArgs e)
{
tabControl1.SelectedIndex = 1;
writer.Close();
outFile.Close();
History history = new History();
history.ShowDialog();
}
private void button1_Click_1(object sender, EventArgs e)
{
FileStream outFile = new FileStream(#"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(outFile);
tabControl1.SelectedIndex = 0;
}
}
}
My Second Form's Code:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class History : Form
{
public History()
{
InitializeComponent();
}
static private FileStream inFile = new FileStream(#"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.Open, FileAccess.Read);
private StreamReader reader = new StreamReader(inFile);
private void History_Load(object sender, EventArgs e)
{
string item;
item = reader.ReadLine();
try
{
lstHistory.Items.Add(item);
}
catch (Exception)
{
lstHistory.Font = new Font(lstHistory.Font.Name, 12, lstHistory.Font.Unit);
lstHistory.Items.Add("You have not rolled any numbers");
}
}
}
}
You need to release the unmanaged resources (in your case the file) properly once done with it. Call the Dispose() function on the stream once done with it:
if(inFile != null){
inFile.Dispose();
}
And even better, wrap it in a using() like this:
using(FileStream outFile = new FileStream(#"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.OpenOrCreate, FileAccess.Write)){
StreamWriter writer = new StreamWriter(outFile);
tabControl1.SelectedIndex = 0;
}
using will automatically call Dispose() for you at the right time in the proper way (i.e. it checks if the object is null first before calling Dispose() on it to avoid a `null exception). Check this link for more details about the using statement.
However, if you have the same code in so many places, it is probably worth it to wrap it in a singleton pattern. Check this Microsoft article on how to write a singleton pattern in C#.

Ink to memorystream problem

I was trying to convert an ink from Microsoft.Ink namespace to memorystream, so to convert it to image, but I don't understand why it's getting an error in the memorystream. I kind of felt that it was an error from Convert.FromBase64String()
But I don't know what other choices I have to convert it to image.
Please help me
Here is my code:
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;
using Microsoft.Ink;
namespace testPaint
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
InkCollector ink;
private void Form1_Load(object sender, EventArgs e)
{
ink = new InkCollector(pictureBox1);
ink.Enabled = true;
ink.AutoRedraw = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
UTF8Encoding utf8 = new UTF8Encoding();
ink.Enabled = false;
string strInk = Convert.ToBase64String(ink.Ink.Save(PersistenceFormat.Base64InkSerializedFormat, CompressionMode.Maximum));
textBox1.Text = strInk;
ink.Enabled = true;
}
private void btnClr_Click(object sender, EventArgs e)
{
ink.Enabled = false;
ink.Ink = new Microsoft.Ink.Ink();
ink.Enabled = true;
pictureBox1.Invalidate();
}
private void btnExport_Click(object sender, EventArgs e)
{
byte[] byImage = Convert.FromBase64String(textBox1.Text);
MemoryStream ms = new MemoryStream();
ms.Write(byImage, 0, byImage.Length);
Image img = Image.FromStream(ms);
img.Save("test.gif", System.Drawing.Imaging.ImageFormat.Gif);
ink.Enabled = true;
}
}
}
The documentation is very preliminary but I think you are probably using the wrong PersistenceFormat tag: you are using Base64 as the output format but you clearly want PersistenceFormat.Gif.
Apart from that, your conversion to and from a string is really not at all meaningful. Just use a private byte[] variable to store the ink data. Furthermore, your detour via a MemoryStream and a System.Graphics.Image makes no sense either.
// using System.IO;
private byte[] inkData;
private void btnSave_Click(object sender, EventArgs e)
{
inkData = ink.Ink.Save(PersistenceFormat.Gif, CompressionMode.Maximum);
}
private void btnExport_Click(object sender, EventArgs e)
{
// Data is already in GIF format, write directly to file!
using (var stream = new FileStream("filename", FileMode.Create, FileAccess.Write))
stream.Write(inkData, 0, inkData.Length);
}

Categories

Resources