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));
}
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();
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"
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 add border in two pivot items.
When my border is added to grid in pivot item for the first time everything is working fine. But when i try to add border second time in same pivot item it throws an exception "The parameter is incorrect"
here is my code :
private void pivot_item1Loaded()
{
WebClient webClient2011 = new WebClient();
string Url2011 = "http://hostname/Details/Images?year=2011" + "&time=" + System.DateTime.UtcNow;
webClient2011.OpenReadAsync(new Uri(Url2011));
webClient2011.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted2011);
}
private void pivot_item2Loaded()
{
WebClient webClient2012 = new WebClient();
string Url2012 = "http://hostname/Details/Images?year=2012" +"&time="+ System.DateTime.UtcNow;
webClient2012.OpenReadAsync(new Uri(Url2012));
webClient2012.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted2012);
}
public void webClient_OpenReadCompleted2011(object sender, OpenReadCompletedEventArgs e)
{
StringBuilder output = new StringBuilder();
try
{
using (XmlReader reader = XmlReader.Create(e.Result))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "iconPath")
{
string iconPath = reader.ReadElementContentAsString();
iconImages2011.Add(iconPath);
}
if (reader.Name == "imagePath")
{
string imagePath = reader.ReadElementContentAsString();
fullScreenImages2011.Add(imagePath);
}
}
}
}
int numOfRows = (iconImages2011.Count) / 3 + 1;
for (int j = 0; j < numOfRows; j++)
{
//pivot_item1
ContentPanel2011.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(150) });
}
int rowCount = 0;
int columnCount = 0;
for (int i = 0; i < iconImages2011.Count; i++)
{
Border border2011 = new Border();
border2011.Background = new SolidColorBrush(Colors.Blue);
border2011.Height = 110;
border2011.Width = 110;
border2011.CornerRadius = new CornerRadius(10);
Canvas canvas2011 = new Canvas();
canvas2011.Height = 110;
canvas2011.Width = 110;
BitmapImage AppImage = new BitmapImage(new Uri(iconImages2011[i], UriKind.Absolute));
Image img = new Image();
img.Source = AppImage;
img.Width = 90;
img.Height = 90;
img.Stretch = Stretch.Fill;
img.Margin = new Thickness(10, 10, 10, 10);
canvas2011.Children.Add(img);
border2011.Child = canvas2011;
border2011.Name = i.ToString();
Grid.SetColumn(border2011, columnCount);
Grid.SetRow(border2011, rowCount);
ContentPanel2011.Children.Add(border2011);
pivot2011.Content = ContentPanel2011;
if (columnCount < 2)
{
columnCount++;
}
else if (columnCount == 2)
{
columnCount = 0;
rowCount++;
}
}
}
catch (Exception x)
{
MessageBox.Show(x.Message);
}
}
This code works for the first time but gives exception after that and ContentPanel2011 viz pivot_item1 do not get filled with border2011
It is done.
just set content property on pivots to null before before setting the content again.
I have just added:
pivot2011.Content = null;
pivot2012.Content = null;
in pivot_item1Loaded() and pivot_item2Loaded()
and it is working fine.
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?