I'm using Controls.Find() method to find a ListBox that i created dynamically. Name of those ListBoxes come from Directories that i created and named uniquely. Everytime i use this method it says the reference is null. How do i get the actual ListBox that i want?
Here is code:
public DosyaTakipAraci()
{
InitializeComponent();
string anaDizin = Properties.Settings.Default.anaDizin;
if (anaDizin == "" || anaDizin == null)
{
dizinSecici.Description = "Lütfen dosyalarınızın kaydedileceği bir dizin seçiniz.";
dizinSecici.ShowDialog();
Properties.Settings.Default.anaDizin = dizinSecici.SelectedPath + #"\";
Properties.Settings.Default.Save();
}
string[] dizinler = Directory.GetDirectories(anaDizin);
if (dizinler.Length > 0)
DizinleriYukle(dizinler);
}
This method loads all Directories
private void DizinleriYukle(string[] dizinler)
{
for (int i = 0; i < dizinler.GetLength(0); i++)
{
DirectoryInfo dizin = new DirectoryInfo(dizinler[i]);
DizinYukleyici(dizin.Name);
}
}
This method is belongs to Directory icon that is created for each Directory
private void DizinSimge_DragDrop(object sender, DragEventArgs e)
{
string[] dosyalar = (string[])e.Data.GetData(DataFormats.FileDrop);
PictureBox simge = (PictureBox)sender;
string dizinAdi = simge.Name;
string anaDizin = Properties.Settings.Default.anaDizin;
foreach (string dosya in dosyalar)
{
string dosyaAdi = Path.GetFileName(dosya);
if (File.Exists($#"{anaDizin}{dizinAdi}\{dosyaAdi}"))
return;
File.Copy(dosya, $#"{anaDizin}{dizinAdi}\{dosyaAdi}", true);
DosyaYukleyici(Panel.Controls.Find(dizinAdi, true).FirstOrDefault() as ListBox);
}
}
This method loads the Directory and creates Controls related to the Directory
private void DizinYukleyici(string dizinAdi)
{
#region Kontrol tanımları
PictureBox dizinSimge = new PictureBox
{
Name = dizinAdi,
Image = Properties.Resources.folder,
Size = new Size(32, 32),
Location = new Point(this.X, this.Y),
AllowDrop = true
};
TextBox dizinBaslik = new TextBox
{
Name = dizinAdi,
Text = dizinAdi,
Location = new Point(this.X + dizinSimge.Width + 5, this.Y + 8),
Font = new Font("Segou UI", 8.25f),
BackColor = this.BackColor,
BorderStyle = BorderStyle.None,
ReadOnly = true
};
ListBox Dosyalar = new ListBox
{
Name = dizinAdi,
Text = null,
Location = new Point(this.X, this.Y + dizinSimge.Height + 5),
BorderStyle = BorderStyle.None,
BackColor = this.BackColor,
Width = dizinSimge.Width + dizinBaslik.Width + 5
};
#endregion
#region Olaylar
dizinSimge.DragEnter += new DragEventHandler(DizinSimge_DragEnter);
dizinSimge.DragDrop += new DragEventHandler(DizinSimge_DragDrop);
dizinBaslik.DoubleClick += new EventHandler(Baslik_DoubleClick);
dizinBaslik.KeyPress += new KeyPressEventHandler(Baslik_Press);
Dosyalar.DragEnter += new DragEventHandler(DizinSimge_DragEnter);
Dosyalar.DragDrop += new DragEventHandler(Dosyalar_DragDrop);
#endregion
Panel.Controls.Add(dizinSimge);
Panel.Controls.Add(dizinBaslik);
Panel.Controls.Add(Dosyalar);
DosyaYukleyici(Dosyalar);
this.X += (short)(dizinSimge.Width + dizinBaslik.Width + 5);
}
This method Loads files of a Directory and adds them to related ListBox
private void DosyaYukleyici(ListBox Liste)
{
string dizinAdi = Liste.Name;
Liste.Items.Clear();
string anaDizin = Properties.Settings.Default.anaDizin;
string dizin = Path.Combine(anaDizin, dizinAdi);
string[] dosyalar = Directory.GetFiles(dizin);
foreach (string dosya in dosyalar)
{
Liste.Items.Add(Path.GetFileName(dosya));
}
}
You give the PictureBox, the TextBox and the ListBox the same name dizinAdi. Now when you search a ListBox, you may find a PictureBox or a TextBox first. Then you try to cast it with as ListBox which yields null if it is not the ListBox.
Filter the by type:
Panel.Controls.Find(dizinAdi, true).OfType<ListBox>().FirstOrDefault()
alternatively, you could give different names to different controls like
"lst" + dizinAdi
"txt" + dizinAdi
"pic" + dizinAdi
or
dizinAdi + "ListBox"
dizinAdi + "TextBox"
dizinAdi + "PictureBox"
Related
I can't find any solution or hint on this problem. Problem described after this code.
I must create one picturebox and radiobutton for every folder found on a specific path:
{
InitializeComponent();
string pathtocircuits = "../../tracks";
string[] allfiles = Directory.GetDirectories(pathtocircuits, "*.*", SearchOption.TopDirectoryOnly);
int imgx = 387;
int imgy = 153;
int radx = 428;
int rady = 259;
String track = "";
String pici = "";
String pic = "pictureBox";
String rad = "radiobutton";
String radr = "";
String picr = "";
foreach (String file in allfiles)
{
track = Path.GetFileName(file);
pici = "../../tracks/" + track + "/p_" + track + ".png";
picr = pic + element.ToString();
radr = rad + element.ToString();
PictureBox pb = new PictureBox();
pb.Location = new System.Drawing.Point(imgx, imgy); ;
pb.Image = Image.FromFile(pici);
pb.Width = 100;
pb.Height = 100;
pb.SizeMode = PictureBoxSizeMode.StretchImage;
pb.Name = picr;
Controls.Add(pb);
RadioButton rdo = new RadioButton();
rdo.Name = radr;
rdo.Text = "";
rdo.Tag = track;
rdo.Location = new Point(radx, rady);
this.Controls.Add(rdo);
element += 1;
imgx += 110;
radx += 110;
}
}
With this part I get to create the elements I need (it works).
My problem is when I press a button to reach Form2. How can I check which radiobutton is selected and store its Tag value in a String?
for(int i = 0; i<element; i++)
{
if( ??? .Checked == true )
{
globalstring = ??? .Tag;
}
}
If I try to use the name of a created radiobutton instead of a ??? it gives me an error like 'element ??? does not have a Checked or Tag attribute'
Add method below
Add to For loop : rdo.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton button = sender as RadioButton;
string name = button.Text;
}
RadioButtons as any other control are stored in the Controls collection of their container. If you add them directly to the form you can retrieve them using this code.
protected void Button1_Click(object sender, EventArgs e)
{
var radio = this.Controls.OfType<RadioButton>().FirstOrDefault(x => x.Checked);
if(radio != null)
{
string tag = radio.Tag.ToString();
.....
// Form2 = new Form2(tag);
}
}
The radiobuttons are added to a same group by default, so you can get the checked radiobutton as followed.
List<RadioButton> radioButtons = this.Controls.OfType<RadioButton>().ToList();
RadioButton rb = radioButtons
.Where(r => r.Checked)
.Single();
string tag = rb.Tag.ToString();
on startup I'm generating a lot of controls 90 to be exact and everything is working ok EXCEPT for the labels they are not being drawn or something? they are there because I can click them and they show proper ID (click event) here's the genereation code
private static bool ClientsLoaded = false;
private static WebBrowser[] Clients = new WebBrowser[45];
private static Label[] ClientLabel = new Label[45];
private static int MaximizedClient = -1;
public Form1()
{
InitializeComponent();
int WBoffsetX = 0;
int WBoffsetY = 0;
int lbloffsetX = 0;
int lbloffsetY = 0;
for (int i = 0; i < 45; i++)
{
var wb = new WebBrowser();
Clients[i] = wb;
wb.ScrollBarsEnabled = false;
wb.Height = 12;
wb.Width = 12;
wb.Location = new Point(2 + WBoffsetX, 2 + WBoffsetY);
WBoffsetX += 13;
wb.ScriptErrorsSuppressed = true;
this.Controls.Add(wb);
ClientLabel[i] = new Label();
ClientLabel[i].Name = "lbl_" + i;
ClientLabel[i].Font = new Font("Arial", 12);
ClientLabel[i].ForeColor = System.Drawing.Color.White;
ClientLabel[i].Location = new Point(12 + lbloffsetX, 450 + lbloffsetY);
lbloffsetX += 22;
ClientLabel[i].Click += new EventHandler(lbl_click);
ClientLabel[i].Text = "C" + i + ": o";
this.Controls.Add(ClientLabel[i]);
}
}
I've tried adding a button with for(45) clientlabel[i].Refresh() and it did nothing I tried changing the visibilty of them all to false and then back to true and nothing however I did find 1 thing interesting if I hide lbl_1 label 2 text will appear if I had label 2 label 3 text will appear but if I change the previous label back to visible they stay invisible textwise
I can click in a line on the form and
private void lbl_click(object sender, EventArgs e)
{
int id = -1;
var s = sender.ToString();
for(int i = 0; i<=45; i++)
{
if (s.Contains("C" + i + ":"))
{
id = i;
}
}
MessageBox.Show("Hello label, " + id);
}
will pop up the proper ids etc
does anyone know what's causing this maybe? or how to fix it
Well, I don't know what is the problem. This code works well enough and it has only marginal differences with the original(AutoSize property, explicit statement of Height and Width, and minor Location adjustment):
for (int i = 0; i < ClientLabel.Length; i++)
{
// Web browsers
WebBrowser wb = new WebBrowser()
{
ScrollBarsEnabled = false,
Height = 12,
Width = 12,
Location = new Point(2 + WBoffsetX, 2 + WBoffsetY),
ScriptErrorsSuppressed = true
};
WBoffsetX += 13;
Clients[i] = wb;
// Labels
Label label = new Label()
{
Name = "label_" + i,
Text = "Data",
AutoSize = true,
Location = new Point(50 + lbloffsetX, 50 + lbloffsetY),
Width = 100,
Height = 20,
Font = new Font("Arial", 12),
ForeColor = System.Drawing.Color.White,
};
label.Click += new EventHandler(lbl_click);
ClientLabel[i] = label;
lbloffsetX += 30;
}
this.Controls.AddRange(Clients);
this.Controls.AddRange(ClientLabel);
Here I am doing a project where questions are presented in images. When the project loads, "start exam" button will be present in the screen. After pressing the button, it should create a picturebox, a textbox and a button for each image from specified path. Then users has to enter the answer in a textbox which is created dynamically. After the dynamic submit button is clicked for every image, the textbox values have to be stored in the listbox. I don't know how get the values from textbox. Can anyone help me out from this?
Here is my code:
PictureBox[] pics = new PictureBox[100];
TextBox[] txts = new TextBox[100];
Button[] butns = new Button[100];
FlowLayoutPanel[] flws = new FlowLayoutPanel[100];
private void button1_Click( Object sender , EventArgs e)
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
flws[i] = new FlowLayoutPanel();
flws[i].Name = "flw" + i;
flws[i].Location = new Point(3,brh);
flws[i].Size = new Size(317,122);
flws[i].BackColor = Color.DarkCyan;
flws[i].BorderStyle = BorderStyle.Fixed3D;
pics[i] = new PictureBox();
pics[i].Location = new Point(953, 95 + brh);
pics[i].Name = "pic" + i;
pics[i].Size = new Size(300, 75);
pics[i].ImageLocation = "C:/" + listBox1.Items[i];
flws[i].Controls.Add(pics[i]);
txts[i] = new TextBox();
txts[i].Name = "txt" + i;
txts[i].Location = new Point(953, 186 + brh);
flws[i].Controls.Add(txts[i]);
butns[i] = new Button();
butns[i].Click += new EventHandler(butns_Click);
butns[i].Text = "submit";
butns[i].Name = "but" + i;
butns[i].Location = new Point(1100, 186 + brh);
flws[i].Controls.Add(butns[i]);
flowLayoutPanel1.Controls.Add(flws[i]);
brh += 130;
}
}
private void butns_Click(object sender, EventArgs e)
{
Button butns = sender as Button;
TextBox txts = sender as TextBox;
listBox2.Items.Add("text values " + txts.Text.ToString());
}
I would create a usercontrol to combine the controls.
Search for "custom usercontrol c#"
Regards.
Try this...
private void butns_Click(object sender, EventArgs e)
{
Button butns = sender as Button;
string btnName = butns.Name;
string Id = btnName.Substring(3);
string txtName = "txt" + Id;
listBox2.Items.Add("text values " + GetValue(txtName));
}
private string GetValue(string name)
{
TextBox txt = new TextBox();
txt.Name = name;
foreach (Control ctl in this.Controls)
{
if (ctl is FlowLayoutPanel)
{
foreach (Control i in ctl.Controls)
{
if (((TextBox)i).Name == txt.Name)
{
txt = (TextBox)i;
return txt.Text;
}
}
}
}
return txt.Text;
}
I am trying to navigate between 2 pages.
For view page there is a list box which i select an item inside it will navigate to "deatils page".
When i press on the back key button of the phone it navigate me from "details page" back to "view page".
But the list box in "view page" is showing the selected item as highlighted.
How can i refresh the "view page" such that the list box will not show anything has been selected.
Code for my key back button of the phone "details page":
private void PhoneApplicationPage_BackKeyPress(object sender,
System.ComponentModel.CancelEventArgs e)
{
string selectedFolderName = selectedFolderName2;
NavigationService.Navigate(
new Uri(
"/DisplaySchedule.xaml?=selectedFolderName2" + selectedFolderName,
UriKind.Relative));
}
Code for my navigated page "viewPage:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
selectedFolderName = "";
if (NavigationContext.QueryString.TryGetValue("selectedFolderName", out selectedFolderName))
selectedFolderName1 = selectedFolderName;
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
//For time
try
{
StreamReader readFileTime = new StreamReader(new IsolatedStorageFileStream(selectedFolderName1 + "\\time.Schedule", FileMode.Open, myStore));
//For title
StreamReader readFileTitle = new StreamReader(new IsolatedStorageFileStream(selectedFolderName1 + "\\title.Schedule", FileMode.Open, myStore));
//For category
StreamReader readFileCategory = new StreamReader(new IsolatedStorageFileStream(selectedFolderName1 + "\\category.Schedule", FileMode.Open, myStore));
String timeText = readFileTime.ReadLine();
timeSplit = timeText.Split(new char[] { '^' });
String titleText = readFileTitle.ReadLine();
titleSplit = titleText.Split(new char[] { '^' });
String categoryText = readFileCategory.ReadLine();
categorySplit = categoryText.Split(new char[] { '^' });
}
catch (Exception)
{
}
//Define grid column, size
Grid schedule = new Grid();
if (scheduleListBox.Items.Count == 0)
{
foreach (var time in timeSplit)
{
timeList = time;
//Column 1 to hold the time of the schedule
ColumnDefinition scheduleTimeColumn = new ColumnDefinition();
GridLength timeGrid = new GridLength(110);
scheduleTimeColumn.Width = timeGrid;
schedule.ColumnDefinitions.Add(scheduleTimeColumn);
//Text block that show the time of the schedule
TextBlock timeTxtBlock = new TextBlock();
timeTxtBlock.Text = time;
//Set the alarm label text block properties - margin, fontsize
timeTxtBlock.FontSize = 28;
timeTxtBlock.Margin = new Thickness(0, 20, 0, 0);
//Set the column that will hold the time of the schedule
Grid.SetColumn(timeTxtBlock, 0);
schedule.Children.Add(timeTxtBlock);
}
foreach (var title in titleSplit)
{
titleList = title;
//Column 2 to hold the title of the schedule
ColumnDefinition scheduleTitleColumn = new ColumnDefinition();
GridLength titleGrid = new GridLength(500);
scheduleTitleColumn.Width = titleGrid;
schedule.ColumnDefinitions.Add(scheduleTitleColumn);
//Text block that show the title of the schedule
TextBlock titleTxtBlock = new TextBlock();
if (title.Length > 10)
{
string strTitle = title.Substring(0, 10) + "....";
titleTxtBlock.Text = strTitle;
}
else
{
titleTxtBlock.Text = title;
}
//Set the alarm label text block properties - margin, fontsize
titleTxtBlock.FontSize = 28;
titleTxtBlock.Margin = new Thickness(0, 20, 0, 0);
//Set the column that will hold the title of the schedule
Grid.SetColumn(titleTxtBlock, 1);
schedule.Children.Add(titleTxtBlock);
}
foreach (var category in categorySplit)
{
categoryList = category;
//Column 3 to hold the image category of the schedule
ColumnDefinition categoryImageColumn = new ColumnDefinition();
GridLength catImgnGrid = new GridLength(70);
categoryImageColumn.Width = catImgnGrid;
schedule.ColumnDefinitions.Add(categoryImageColumn);
TextBlock categoryTxtBlock = new TextBlock();
categoryTxtBlock.Text = category;
//set the category image and its properties - margin, width, height, name, background, font size
Image categoryImage = new Image();
categoryImage.Margin = new Thickness(-50, 15, 0, 0);
categoryImage.Width = 50;
categoryImage.Height = 50;
if (category == "Priority")
{
categoryImage.Source = new BitmapImage(new Uri("/AlarmClock;component/Images/exclamination_mark.png", UriKind.Relative));
}
else
if (category == "Favourite")
{
categoryImage.Source = new BitmapImage(new Uri("/AlarmClock;component/Images/star_full.png", UriKind.Relative));
}
Grid.SetColumn(categoryImage, 2);
schedule.Children.Add(categoryImage);
}
scheduleListBox.Items.Add(schedule);
}
}
private void scheduleListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//Get the value of selected index in scheduleListBox
int selectedIndexOfSchedule = scheduleListBox.SelectedIndex;
NavigationService.Navigate(new Uri("/ViewScheduleDetails.xaml?selectedIndexOfSchedule=" + selectedIndexOfSchedule + "&selectedFolderName1=" + selectedFolderName1, UriKind.Relative));
}
simply unselect a item?
myListBox.SelectedItem = -1;
After selecting an item simply remove the selection. (See comments below in CAPS)
private void scheduleListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//Get the value of selected index in scheduleListBox
int selectedIndexOfSchedule = scheduleListBox.SelectedIndex;
// RESET THE SELECTED INDEX/ITEM
scheduleListBox.SelectedIndex = -1;
// OR
scheduleListBox.SelectedItem = null;
NavigationService.Navigate(new Uri("/ViewScheduleDetails.xaml?selectedIndexOfSchedule=" + selectedIndexOfSchedule + "&selectedFolderName1=" + selectedFolderName1, UriKind.Relative));
}
I am having a weird experience. I am dynamically creating a row of textboxes at runtime when the user clicks a button.
However, on my local machine the text boxes appear correctly (example
[TextBox1] [TextBox2] [TextBox3] [TextBox4] [TextBox5]
[TextBox1] [TextBox2] [TextBox3] [TextBox4] [TextBox5]
[TextBox1] [TextBox2] [TextBox3] [TextBox4] [TextBox5]
When I run this app on the production, the output side-by-side is:
[TextBox1][TextBox1] [TextBox2][TextBox2] [TextBox3][TextBox3] [TextBox4][TextBox4]
The output should be one row of textboxes, then a second row of 5 text boxes etc.
The code that builds the textboxes is:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
dyntxtCar = new TextBox[myCount];
dyntxtMake = new TextBox[myCount];
dyntxtMileage = new TextBox[myCount];
dyntxtVIN = new TextBox[myCount];
dyntxtSLIC = new TextBox[myCount];
dyntxtPlateNumber = new TextBox[myCount];
for (i = 0; i < myCount; i += 1)
{
TextBox txtCar = new TextBox();
TextBox txtMake = new TextBox();
TextBox txtMileage = new TextBox();
TextBox txtVIN = new TextBox();
TextBox txtSLIC = new TextBox();
TextBox txtPlateNumber = new TextBox();
txtCar.ID = "txtVehCar" + i.ToString();
txtMake.ID = "txtVehMake" + i.ToString();
txtMileage.ID = "txtVehMilage" + i.ToString();
txtVIN.ID = "txtVehVIN" + i.ToString();
txtSLIC.ID = "txtVehSLIC" + i.ToString();
txtPlateNumber.ID = "txtVehPlate" + i.ToString();
//Set tabIndex values for dynamic text fields;
txtCar.TabIndex = System.Convert.ToInt16(i * 10 + 1);
txtMake.TabIndex = System.Convert.ToInt16(i * 10 + 2);
txtMileage.TabIndex = System.Convert.ToInt16(i * 10 + 3);
txtVIN.TabIndex = System.Convert.ToInt16(i * 10 + 4);
txtSLIC.TabIndex = System.Convert.ToInt16(i * 10 + 5);
txtPlateNumber.TabIndex = System.Convert.ToInt16(i * 10 + 6);
//Set maxlength for dynamic fields;
txtCar.MaxLength = System.Convert.ToInt16(7);
txtVIN.MaxLength = System.Convert.ToInt16(17);
txtSLIC.MaxLength = System.Convert.ToInt16(4);
//Set width of text boxes
txtCar.Width = System.Convert.ToInt16("65");
txtMileage.Width = System.Convert.ToInt16("50");
txtVIN.Width = System.Convert.ToInt16("220");
txtSLIC.Width = System.Convert.ToInt16("45");
//txtPlateNumber.Width = System.Convert.ToInt16("35");
phCar.Controls.Add(txtCar);
phMake.Controls.Add(txtMake);
phMileage.Controls.Add(txtMileage);
phVIN.Controls.Add(txtVIN);
phSLIC.Controls.Add(txtSLIC);
phPlateNumber.Controls.Add(txtPlateNumber);
dyntxtCar[i] = txtCar;
dyntxtMake[i] = txtMake;
dyntxtMileage[i] = txtMileage;
dyntxtVIN[i] = txtVIN;
dyntxtSLIC[i] = txtSLIC;
dyntxtPlateNumber[i] = txtPlateNumber;
LiteralControl literalBreak = new LiteralControl("<br />");
phCar.Controls.Add(literalBreak);
phMake.Controls.Add(literalBreak);
phMileage.Controls.Add(literalBreak);
phVIN.Controls.Add(literalBreak);
phSLIC.Controls.Add(literalBreak);
phPlateNumber.Controls.Add(literalBreak);
}
}
protected void Page_PreInit(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
if ((myControl != null))
{
if ((myControl.ClientID.ToString() == "btnAddTextBox"))
{
myCount = myCount + 1;
}
}
}
public static Control GetPostBackControl(Page thePage)
{
Control myControl = null;
string ctrlName = thePage.Request.Params.Get("__EVENTTARGET");
if (((ctrlName != null) & (ctrlName != string.Empty)))
{
myControl = thePage.FindControl(ctrlName);
}
else
{
foreach (string Item in thePage.Request.Form)
{
Control c = thePage.FindControl(Item);
if (((c) is System.Web.UI.WebControls.Button))
{
myControl = c;
}
}
}
return myControl;
}
Anyone experience this?