Here's the error:
It says the source of the exception is on Line20 of my class. Here is my class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
namespace WebServiceScanner
{
public partial class imageList : UserControl
{
private int XPosition = 0;
public imageList()
{
InitializeComponent();
Images.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Images_CollectionChanged);
}
public ObservableCollection<selectablePicture> Images { get; set; }
public void AddImage(selectablePicture image)
{
Images.Add(image);
}
public void RemoveImage(selectablePicture image)
{
Images.Remove(image);
}
public void MoveImageLeft(int index)
{
selectablePicture tmpImage = Images[index];
Images[index] = Images[index - 1];
Images[index - 1] = tmpImage;
}
public void MoveImageRight(int index)
{
selectablePicture tmpImage = Images[index];
Images[index] = Images[index + 1];
Images[index + 1] = tmpImage;
}
void Images_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
RedrawImages();
}
private void RedrawImages()
{
foreach (var picture in Images)
{
picture.Location = new Point(XPosition + panel1.AutoScrollPosition.X, 0);
XPosition += 130;
panel1.Controls.Add(picture);
}
}
}
}
Maybe I'm doing something dumb like setting an event handler at the constructor. Any ideas? This user control isn't really that complex, so there are few places where something could be wrong.
If you guys need more information please let me know.
Add a statement to instantiate Images.
public imageList()
{
InitializeComponent();
Images = new ObservableCollection<selectablePicture>();
Images.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Images_CollectionChanged);
}
I'm guessing it is something to do with the fact that Images isn't set to any value so the control is trying to render it for DesignView but Images is null hence the NullReferenceException. It's probably the code in the Constructor when it tries to register against the Images which will probably run before any injection code setting images.
Does < selectablePicture > have a parameterless public constructor? And are you instancing Images?
Related
I have the following form with a method called setIndex
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;
namespace ProjectName
{
public partial class SettingsWindow : Form
{
internal readonly static SettingsWindow Instance = new SettingsWindow { Visible = false };
public SettingsWindow()
{
InitializeComponent();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string defaultsearch = listBox1.GetItemText(listBox1.SelectedItem);
Core.RegistryHelper.SaveSetting("Config", "ds", defaultsearch);
if (defaultsearch == "aaa") {
Core.LandingUrlOrig = Core.DomainName + "/defaulturl1.php";
} else {
Core.LandingUrlOrig = Core.DomainName + "/defaulturl2.php";
}
}
public static void setIndex(int i)
{
listBox1.SelectedIndex = i;
}
On another form called MainWindow during its initialization I call:
public MainWindow()
{
SettingsWindow.setIndex(0);
}
The error I get is:
An object reference is required for the non-static field, method, or property 'SettingsWindow.listBox1'
Initially the listbox method wasn't static and thus invisible from MainWindow. But now, listbox appears to not exist, even if the form has been instantiated. How do I solve this? I'm just learning C#.
Thank you in advance
because the function setIndex is static you need to use the Instance property:
public static void setIndex(int i)
{
Instance.listBox1.SelectedIndex = i;
}
or don't make that function static and then use instance in the mainwindow function:
public void setIndex(int i)
{
listBox1.SelectedIndex = i;
}
public MainWindow()
{
SettingsWindow.Instance.setIndex(0);
}
Just started learning Visual Studio and I'm trying to make a soundboard in Windows Forms.
ButtonMaker(); is the function I use to make a button for each soundfile in my directory so I don't have to make 70 different buttons for every sound, but when I run the program nothing shows up in the forms window. Anybody know why? I've tried calling the function in Main() and in the initial Form1 class but nothing happens in either. Forms class file here:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MySoundBoard
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
///Tried running it here
}
private void Form1_Load(object sender, EventArgs e)
{
///Tried running it here
}
private void ButtonMaker()
{
string[] files = Soundfiles.GetFile();
foreach (var item in files)
{
string btnName = item.ToUpper();
Button btNname = new Button();
btNname.Text = item;
int x = 40;
int y = 40;
btNname.Location = new Point(x, y);
x = x + 50;
if (x>900)
{
x = 40;
y = y + 30;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
Here is the SoundFiles class:
using System.IO;
using System;
using System.Text;
using System.Diagnostics;
using WMPLib;
namespace MySoundBoard
{
class Soundfiles {
WMPLib.WindowsMediaPlayer Player;
static public string[] GetFile() {
string txtPath = #"C:\Documents\path\to\sound effects";
string[] files =
Directory.GetFiles(txtPath, "*ProfileHandler.cs", SearchOption.TopDirectoryOnly);
return files;
}
public void PlayFile(String url)
{
Player = new WMPLib.WindowsMediaPlayer();
Player.URL = url;
Player.controls.play();
}
}
}
And the main project file(not that worked with yet):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MySoundBoard
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
///Tried running it here
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
As said, I'm very new to this language and any help would be appriciated!
You create the buttons but never add them to the form. Just add
this.Controls.Add(btNname);
The next thing is, that your buttons will not do something. You'll need to add an event handler as well.
btNname.Click += ...;
In order to know which button plays which sound, you need to find a way to have that association. A hacky approach is
btNname.Tag = item;
and then evaluate Tag later
so my issue is that, I can´t make my DataGridView read information from a text file already created, don´t know what to do really, I am kinda new to C#, so I hope you can help me :D
Here is my code to save the values from my grid:
private void buttonGuardar_Click(object sender, EventArgs e)
{
string[] conteudo = new string[dataGridView1.RowCount * dataGridView1.ColumnCount];
int cont = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
conteudo[cont++] = cell.Value.ToString();
}
}
File.WriteAllLines("dados.txt", conteudo);
And now, from a different form, there is another Grid that must be fill with the values saved in that File
The present code:
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 WindowsFormsApplication31
{
public partial class Form3 : Form
{
DateTime start, end;
private void Form3_Load(object sender, EventArgs e)
{
textBox1.Text = start.ToString("dd-MM-yyyy");
textBox2.Text = end.ToString("dd-MM-yyyy");
}
public Form3(DateTime s, DateTime e)
{
InitializeComponent();
start = s;
end = e;
}
}
}
In conclusion, both of the grid should have 4 Cells:
0-Designação
1-Grupo
2-Valor
3-Data
And the second one from Form3, should read the text file, in the right order
Hope you can help me, Thanks.
Please try this below.
I have exported the grid data in to a text file as same structure as how it appears in grid as below.
private void button1_Click(object sender, EventArgs e)
{
TextWriter writer = new StreamWriter("Text.txt");
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
for (int j = 0; j < DataGridView1.Columns.Count; j++)
{
writer.Write(DataGridView1.Rows[i].Cells[j].Value.ToString() + "\t");
}
writer.WriteLine("");
}
writer.Close();
}
Created a new class with properties as the column names and a method to load the exported data into a list collection of class as shown below.Here in this example ,my grid has two columns Name and Marks.so i declared those two properties in my user class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WindowsFormsApplication1
{
public class User
{
public string Name { get; set; }
public string Marks { get; set; }
public static List<User> LoadUserListFromFile(string path)
{
var users = new List<User>();
foreach (var line in File.ReadAllLines(path))
{
var columns = line.Split('\t');
users.Add(new User
{
Name = columns[0],
Marks = columns[1]
});
}
return users;
}
}}
Now on the form load event of second form,call the above method and bind to the second grid as shown below
private void Form2_Load(object sender, EventArgs e)
{
dataGridView2.DataSource = User.LoadUserListFromFile("Text.txt");
}
Pleas mark this as answer,if it helps.
I'm having a trouble in my code with this exception:
System.FormatException
Additional information: Input string was not in a correct format.
I have two files in my visual studio C# solution:
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventPubSub
{
class Program
{
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
// Subscribe to the Changed event
rect.Changed += new EventHandler(Rectangle_Changed);
rect.Length = 10;
}
static void Rectangle_Changed(object sender, EventArgs e)
{
Rectangle rect = (Rectangle)sender;
Console.WriteLine("Value Changed: Length = { 0}", rect.Length);
}
}
}
file Rectangle.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventPubSub
{
class Rectangle
{
//Declare an event named Changed of
//delegate type EventHandler
public event EventHandler Changed;
private double length = 5;
public double Length
{
get
{
return length;
}
set
{
length = value;
//Publish the Changed event
Changed(this, EventArgs.Empty);
}
}
}
}
The exception arise when I execute the line: rect.Length = 10;
there is a space between { and 0 in the handler which is leading to the exception
Please change the event handler like this, all will work fine
static void Rectangle_Changed(object sender, EventArgs e)
{
Rectangle rect = (Rectangle)sender;
Console.WriteLine(string.Format("Value Changed: Length = {0}", rect.Length));
}
I have made 2 changes here -
Added a string.Format (which is not the problem)
removed the space between { & 0. it was { 0} now I made it {0} (which is the actual problem)
Try first adding try catch to catch the error it is throwing. So you could identify and fix it. This is just to help you fix your own problem next time. :)
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
string errorMessage = String.empty;
try
{
// Subscribe to the Changed event
rect.Changed += new EventHandler(Rectangle_Changed);
rect.Length = 10;
}
catch(Exception ex)
{
errorMessage = ex.Message;
}
}
I want to create a method which makes my application wait X number of seconds, then continues on down a line of scripts. For example, this is the code that I have so far, after reading many similar help topics:
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
methods.WriteTextToScreen(label1, "Hello!");
methods.sleepFor(1);
methods.WriteTextToScreen(label1, "Welcome!");
methods.sleepFor(1);
methods.WriteTextToScreen(label1, "Allo!");
}
public class methods
{
public static int timeSlept;
public static void WriteTextToScreen(Label LabelName, string text)
{
LabelName.Text = text;
}
public static void sleepFor(int seconds)
{
timeSlept = 0;
System.Timers.Timer newTimer = new System.Timers.Timer();
newTimer.Interval = 1000;
newTimer.AutoReset = true;
newTimer.Elapsed += new System.Timers.ElapsedEventHandler(newTimer_Elapsed);
newTimer.Start();
while (timeSlept < seconds)
{
Application.DoEvents();
}
Application.DoEvents();
}
public static void newTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timeSlept = IncreaseTimerValues(ref timeSlept);
Application.DoEvents();
}
public static int IncreaseTimerValues(ref int x)
{
int returnThis = x + 1;
return returnThis;
}
}
}
}
What I want to do is have my program do the methods.WriteTextToScreen(label1, "Hello!")
then wait for 1 second, then continue on in the same fashion. The problem is that the Form I'm displaying the text on doesn't show up at all until it has written "Allo!" onto the screen, so the first time it appears it already says that. Am I doing something wrong, or is there just no way to do this?
The form doesn't show until it has been constructed i.e. all the code in Form1 is run. See here for info on form constructors: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.form.aspx
To fix your problem you could move the writeTextToScreen and sleep code into the forms on load method. See http://msdn.microsoft.com/en-us/library/system.windows.forms.form.onload.aspx