Dynamically creating Link Labels using foreach in c# - c#

I am trying to create link labels dynamically using foreach . I am setting the text of each linklabel to a string which is stored in flatestgames string array and whose links are stored in flatestlinks string array.
But it is throwing a null reference exception at the line flg[i].Text = s though s is not set to null.
Please help me out.
Below is the code snippet:
if (!(flatestgames == null || flatestgames.Length < 1))
{
i = 0;
LinkLabel[] flg = new LinkLabel[10];
foreach (string s in flatestgames)
{
flg[i].Text = s;
flg[i].Links.Add(0, s.Length, flatestlinks[i]);
Point p = new Point(43, 200 + 23 * i);
flg[i].Location = p;
flg[i].Visible = true;
flg[i].Show();
this.Controls.Add(flg[i]);
i++;
}
}

Try flg[i] = new LinkLabel(); in foreach loop
if (!(flatestgames == null || flatestgames.Length < 1))
{
i = 0;
LinkLabel[] flg = new LinkLabel[10];
foreach (string s in flatestgames)
{
flg[i] = new LinkLabel();
flg[i].Text = s;
flg[i].Links.Add(0, s.Length, flatestlinks[i]);
Point p = new Point(43, 200 + 23 * i);
flg[i].Location = p;
flg[i].Visible = true;
flg[i].Show();
this.Controls.Add(flg[i]);
i++;
}
}

Are you sure, that the length of your flatestgames array less than 10? You have to check this at first and declare your:
LinkLabel[] flg = new LinkLabel[10];
as:
LinkLabel[] flg = new LinkLabel[flatestgames.Length];
I think you get this exception, because in foreach you try to get more than 10 entities as you declared.

Related

How to find a WpfCell in a WpfTable with a selected value?

I'm making with Visual Studio 2013 Coded UI Tests for the WPF-application of my company.
In that application we have - per example - a mask with the RadGridView from Telerik which contains a list with all users.
Because the application is still in development, i want to create generic methods.
In case of the mask with the userlist, i want to call a method, which i give the control, the cellId and the cellValue.
Coded UI recognizes the following hierarchy:
WpfTable - WpfRow - WpfText
Further i cannot see all user entries in the grid, which means, i have to scroll down while searching.
So i have programmed the following method:
private void SearchRowAndCell(WpfTable table, string cellId, string cellValue)
{
int n = 0;
int maxIndex = table.RowCount;
while (n < maxIndex)
{
var row = new WpfRow(table);
var rowIdForSearch = "Row_" + n;
row.SearchProperties.Add("AutomationId", rowIdForSearch);
UITestControlCollection foundRows = row.FindMatchingControls();
if (foundRows.Count > 0)
{
row = (WpfRow)foundRows[0];
var cell = new WpfCell(row);
var cellIdForSearch = "Cell_" + n + "_" + cellId;
cell.SearchProperties.Add("AutomationId", cellIdForSearch);
UITestControlCollection foundCells = cell.FindMatchingControls();
if (foundCells.Count > 0)
{
cell = (WpfCell)foundCells[0];
var text = new WpfText(cell);
text.SearchProperties.Add("DisplayText", cellValue);
UITestControlCollection foundTexts = text.FindMatchingControls();
if (foundTexts.Count > 0)
{
text = (WpfText)foundTexts[0];
Mouse.DoubleClick(row, new Point(10, 10));
n = maxIndex;
}
else
{
Keyboard.SendKeys(row, "{Down}", ModifierKeys.None);
}
}
}
n++;
}
}
Now my problem is, that i get an exception when i try to get the WpfText control because "DisplayText" is not a search property.
When i try "Value" instaed of "DisplayText" i find nothing.
Which search property do i need to find the WpfText with the selected value?
Thanks in advance!
you can try using the following :
WpfTable t = new WpfTable();
t.FindFirstCellWithValue(cellValue);
the 'FindFirstCellWithValue()' method is a wpfTable built in method
I guess you can just iterate over the cell contents and find the WpfText and then use string compare:
var cellContents = cell.GetChildren();
if (cellContents == null || cellContents.Count < 0) continue;
foreach (var content in cellContents)
{
WpfText wpfText = content as WpfText;
if (wpfText != null && wpfText.DisplayText.Equals(cellValue, StringComparison.OrdinalIgnoreCase))
{
Mouse.DoubleClick(row, new Point(10, 10));
}
}

Textbox SpellCheck.IsEnabled - How to count

My Textbox needs to work out the number of spelling errors occur in a textbox.
My research has shown me how to get the spelling errors to work, using
<TextBox Text="{Binding Content}" SpellCheck.IsEnabled="True" Language="en-GB" />
I was slightly annoyed that I can't have IsReadOnly set to true but, I guess I have to live with it.
What I can't find out is how to know how many spelling issues/errors are in the Textbox. All I can find is http://msdn.microsoft.com/en-us/library/system.windows.controls.spellcheck%28v=vs.110%29.aspx which doesn't say it does but I'm not losing hope!
I tried to add
TextBox tx = new TextBox();
tx.SpellCheck.IsEnabled = true;
tx.Text = "saf and tre";
var split = tx.Text.Split(' ');
var errors = 0;
foreach (var s in split)
{
var tempTb = new TextBox();
tempTb.Text = s;
SpellingError e = tempTb.GetSpellingError(0); // always null
var a = tempTb.GetSpellingErrorLength(0);
var b = tempTb.GetSpellingError(0);
var c = tempTb.GetSpellingErrorStart(0);
if ( tempTb.GetSpellingErrorLength(0) >= 0)
errors++;
}
If I update the code from
SpellingError e = tempTb.GetSpellingError(0); // always null
to
SpellingError e = tx.GetSpellingError(0); // not null
Then it provides suggestions which then informs me it's wrong (and I can perform a count).
To get around the issue I'm having to do
TextBox tx = new TextBox();
tx.SpellCheck.IsEnabled = true;
tx.Text = "saf many tre further more i sense taht nothing is what is";
var split = tx.Text.Split(' ');
var errors = 0;
var start = 0;
foreach (var s in split)
{
var tempTb = new TextBox();
tempTb.Text = s;
SpellingError f = tx.GetSpellingError(start);
start += s.Length + 1;
if (f!=null)
errors++;
}
Why does it not work for tempTb?
It appears from my debugging that #EdSF is correct and SpellCheck.IsEnabled must be set for the temporary TextBox
Code used to reproduce this:
void initTest()
{
TextBox tx = new TextBox();
tx.SpellCheck.IsEnabled = true;
tx.Text = "saf and tre";
var split = tx.Text.Split(' ');
var errors = 0;
foreach (var s in split)
{
var tempTb = new TextBox();
tempTb.SpellCheck.IsEnabled = true; // Added this line
tempTb.Text = s;
SpellingError e = tempTb.GetSpellingError(0); // no longer always null
var a = tempTb.GetSpellingErrorLength(0);
var b = tempTb.GetSpellingError(0);
var c = tempTb.GetSpellingErrorStart(0);
//if (tempTb.GetSpellingErrorLength(0) >= 0) //doesn't appear to be correct
if (e != null)
{
errors++;
}
}
}
I found it after I posted
There is
GetSpellingErrorStart()
GetSpellingError()
GetSpellingErrorLength()
SpellingError e = tempTb.GetSpellingError(0);
EG
TextBox tx = new TextBox();
tx.SpellCheck.IsEnabled = true;
tx.Text = "saf";
var reslt = tx.GetSpellingErrorStart(0);

How to get data from SqlDataReader to Array of arrays or Array of strings

I'm trying to populate an array of arrays from a SqlDataReader, but in the end all rows of the array are filled with the same array of numbers.
Here's my T-SQL code:
SELECT
SUM(memberAttendants),
Groups.Name,
DATEPART(wk,convert(datetime,convert(varchar,StatisticsDate),104))
FROM
Stat.dbo.GroupStatistics
INNER JOIN
Stat.dbo.Groups ON GroupStatistics.GroupID = Groups.GroupID
WHERE
(Groups.OrganizationID = '4960')
GROUP BY
Groups.Name, convert(datetime, convert(varchar, StatisticsDate), 104)
ORDER BY
Groups.Name, convert(datetime, convert(varchar, StatisticsDate), 104)
C# code:
SqlDataReader myReader1 = cmd1.ExecuteReader();
if (myReader1.HasRows)
{
int i = 0, j = 0;
string[] Name;
Name = new string[100];
int[][] MainArray = new int[100][];
int[] ActivityArray;
ActivityArray = new int[52];
int[] WeekOfActivity;
WeekOfActivity = new int[52];
bool myFlag = false;
for (int myCounter = 0; myCounter <= myReader1.FieldCount; myCounter++)
{
Aktivitet[myCounter] = new int[myCounter];
}
while (myReader1.Read())
{
if (!myReader1.IsDBNull(0) && !myReader1.IsDBNull(1))
{
if (i == 0 || myReader1.GetString(1) == Name[i-1] || myFlag == true)
{
if (myFlag == true && myReader1.GetString(1) != Name[i-1])
{
i = 0;
MainArray[j] = ActivityArray;
}
myFlag = false;
ActivityArray[i] = myReader1.GetInt32(0);
Name[i] = myReader1.GetString(1);
i++;
}
else
{
MainArray[j] = ActivityArray;
j++;
i = 0;
Name[i] = myReader1.GetString(1);
ActivityArray[i] = myReader1.GetInt32(0);
i++;
myFlag = true;
}
}
}
MainArray[j] = ActivityArray;
How can I fill the MainArray without the last ActivityArray overwrite all the rows in MainArray?
Tnx
What you're missing here is that an array is a reference type. So when you say:
MainArray[j] = ActivityArray
You're setting the entry in MainArray to point to ActivityArray. You never create a new ActivityArray, so they all point to the same place.
Because you're over-writing the content of ActivityArray, you're effectively over-writing all entries in MainArray (because they are all the same entry).
So, you probably want
while (myReader1.Read())
{
ActivityArray = new int[52];
if (!myReader1.IsDBNull(0) && !myReader1.IsDBNull(1))
{
The reason I have put probably is because it's not really that clear to me what your code is trying to do.

NullReferenceException was unhandled Object reference not set to an instance of an object. c#

I tried running my program, and have also compared my code to my friend's code, but the error keeps on showing up even though we tried changing these lines (which I think where the error is coming from):
try
{
FileStream b = new FileStream(#"C:\User\User_2\Desktop\board.txt", FileMode.Open);
StreamReader stream = new StreamReader(b);
int x = 0;
while (!stream.EndOfStream)
{
if (x == 0)
g1 = stream.ReadLine().Split(' ');
else if (x == 1)
g2 = stream.ReadLine().Split(' ');
else if (x == 2)
g3 = stream.ReadLine().Split(' ');
x++;
}
stream.Close();
b.Close();
}
catch (Exception e) { }
The program is used to check for a text file which contains these 3 lines:
O . X
X O .
X . O
...and see if there is a winner.
This is the part where Visual Studio highlights the error:
int n = 0;
int m = n + 1;
int o = m + 1;
Boolean result = false;
int winner = 0;
string dw = "";
while (n <= 2)
{
// In this if-statement is the error:
if (g1[n].Equals(g2[n]) && g2[n].Equals(g3[n]) && !g1[n].Equals("."))
{
result = true;
winner++;
dw = g1[n];
}
if (g1[n].Equals(g1[m]) && g1[m].Equals(g1[o]) && !g1[n].Equals("."))
{
result = true;
winner++;
dw = g1[n];
}
else if (g2[n].Equals(g2[m]) && g2[m].Equals(g2[o]) && !g2[n].Equals("."))
{
result = true;
winner++;
dw = g2[n];
}
else if (g3[n].Equals(g3[m]) && g3[m].Equals(g3[o]) && !g3[n].Equals("."))
{
result = true;
winner++;
dw = g3[n];
}
else if (g1[n].Equals(g2[m]) && g2[m].Equals(g3[o]) && !g1[n].Equals("."))
{
result = true;
winner++;
dw = g1[n];
}
else if (g3[n].Equals(g2[m]) && g2[m].Equals(g1[o]) && !g3[n].Equals("."))
{
result = true;
winner++;
dw = g3[n];
}
n++;
}
I really don't know what to do know, I can't make it work.
EDIT: I tried printing out the values of the arrays before the if statements but it doesn't print anything out. Sorry guys, I'm really new here.
First of all, try reading the file like this:
using System.IO;
try
{
var file = #"C:\User\User_2\Desktop\board.txt";
var lines = File.ReadAllLines(file).ToList();
var g1 = lines[0].Split(' ');
var g2 = lines[1].Split(' ');
var g3 = lines[2].Split(' ');
}
catch (Exception e)
{
throw e;
}
Probably now you'll get an exception thrown.
The line catch (Exception e) { } is the culprit for not being notified that there is an exception. You should always handle the exceptions that you catch in your code.
P.S. Probably you have to use C:\Users\... in the path, instead of C:\User\.... Anyway, make sure that you use a valid path to your file.
When using Equals you must ensure the object you are calling is not null;
object oneValue = 1;
object nullValue = null;
var result = nullValue.Equals(oneValue); // Throws NullReferenceException because nullValue is null
You could use the equality operator instead.
string oneValue = "1";
string nullValue = null;
var result = nullValue == oneValue; // False
You can use the == operator instead of the Equals method, which needs the object to be instantiated. But then you still need to make sure the value isn't null.

How to access multiple buttons or textbox or any control?

I want to access multiple textbox name textbox1,textbox2,textbox3, etc.. by loop not by individual name. For that reason I created one function which create this var names.
public string[] nameCre(string cntrlName, int size)
{
string[] t = new string[size];
for (int i = 0; i < size; i++)
{
t[i] = cntrlName.ToString() + (i + 1);
}
return t;
}
for nameCre("Textbox",5); So this,function successfully returning me TextBox1, TextBox2 ... TextBox5.
But when I am trying to convert this string to TextBox control by
string[] t = new string[50];
t= nameCre("TextBox",5);
foreach (string s in t)
{
((TextBox) s).Text = "";
}
it giving me error :
Cannot convert type 'string' to 'System.Windows.Forms.TextBox'....
How can I accomplish this job?
var t = nameCre("TextBox",5);
foreach (var s in t)
{
var textBox = new TextBox {Name = s, Text = ""};
}
string[] t= new string[50];
t= nameCre("TextBox",5);
foreach (string s in t){
TextBox tb = (TextBox)this.Controls.FindControl(s);
tb.Text = "";
}
if you have many text boxes
foreach (Control c in this.Controls)
{
if (c.GetType().ToString() == "System.Windows.Form.Textbox")
{
c.Text = "";
}
}
Perhaps you need this -
string[] t = new string[50];
t = nameCre("TextBox", 5);
foreach (string s in t)
{
if (!string.IsNullOrEmpty(s))
{
Control ctrl = this.Controls.Find(s, true).FirstOrDefault();
if (ctrl != null && ctrl is TextBox)
{
TextBox tb = ctrl as TextBox;
tb.Text = "";
}
}
}
This post is quite old, anyway I think I can give you (or anyone else with a problem like that) an answer:
I think using an Array (or List) of TextBoxs would be the best solution for doing that:
// using an Array:
TextBox[] textBox = new TextBox[5];
textBox[0] = new TextBox() { Location = new Point(), /* etc */};
// or
textBox[0] = TextBox0; // if you already have a TextBox named TextBox0
// loop it:
for (int i = 0; i < textBox.Length; i++)
{
textBox[i].Text = "";
}
// using a List: (you need to reference System.Collections.Generic)
List<TextBox> textBox = new List<TextBox>();
textBox.Add(new TextBox() { Name = "", /* etc */});
// or
textBox.Add(TextBox0); // if you already have a TextBox named TextBox0
// loop it:
for (int i = 0; i < textBox.Count; i++)
{
textBox[i].Text = "";
}
I hope this helps :)

Categories