I can't connect my XML file and my C# in microsoft visual studio. How do I solve this?
Here you find what need to be in your DA
public class LeegstaandXML
{
public string Index { get; set; }
public string Aard { get; set; }
public string Adres { get; set; }
public static int intElementsCount;
private List<LeegstaandXML> _leegstaand;
public List<LeegstaandXML> Lleegstaand
{
get
{
XmlDocument doc = new XmlDocument();
doc.Load("Lijst_leegstaande_bedrijfspanden.xml");
XmlNodeList elementlist = doc.GetElementsByTagName("fme:Lijst_leegstaande_bedrijfspanden");
intElementsCount = elementlist.Count;
_leegstaand = new List<LeegstaandXML>();
_leegstaand.Add(new LeegstaandXML()
{
Index = elementlist[Form1.counter]["fme:Dossier_ID"].InnerXml,
Adres = elementlist[Form1.counter]["fme:Adres"].InnerXml,
Aard = elementlist[Form1.counter]["fme:Aard_van_het_gebouw"].InnerXml,
});
return _leegstaand;
}
set
{
_leegstaand = value;
}
}
}
This is your connection in your form
private void btnVullen_Click(object sender, EventArgs e)
{
Leegstaand p = new Leegstaand();
do
{
counter++;
LeegstaandXML leegstaand2 = new LeegstaandXML();
foreach(LeegstaandXML lp in leegstaand2.Lleegstaand)
{
leegstaandDA NewItem = new leegstaandDA(lp.Index, lp.Adres, lp.Aard);
NewItem.AddItem();
//ListViewItem item = new ListViewItem(new string[] { lp.id.ToString(), lp.aard, lp.adres, lp.index.ToString() });
// item.Tag = lp;
//lsvLeegstaand.Items.Add(item);
}
} while (counter < LeegstaandXML.intElementsCount -1);
MessageBox.Show("implementatie is geslaagd");
counter = 0;
leegstaandDA.Getleegstaand();
foreach (Leegstaand l in leegstaandDA.Getleegstaand())
{
ListViewItem item = new ListViewItem(new string[] { l.index.ToString(), l.adres, l.aard});
item.Tag = l;
lsvLeegstaand.Items.Add(item);
}
}
Related
So I have a DataGrid which is bound to a ICollectionView.
Now, I have one column which I want it to be bound not to the ICollectionView, but to a local variable from inside of the class.
How do I make that in the code?
<DataGrid
x:Name="DG_StudentsList"
FontSize="20"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Id}" Header="מ''ס"/>
<DataGridTextColumn Binding="{Binding Name}" Header="שם"/>
<DataGridTextColumn Binding="{Binding PhoneNum}" Header="טלפון"/>
<DataGridTemplateColumn Header="ספרים מושאלים">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=BorrowedBooks}" DisplayMemberPath="BookName" SelectionChanged="CB_BookName_SelectionChanged"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Just to be clear, I want to add a new DataGridTextColumn which is the one that will be bound to the local variable.
public partial class StudentsList : Window
{
ObservableCollection<Student> OBStudents = new ObservableCollection<Student>();
CollectionViewSource StudentsCollection;
Predicate<object> yourCostumFilter;
ICollectionView Itemlist;
Student s = Student.Instance;
//string ss = "wel welwel";
public StudentsList()
{
InitializeComponent();
InitializeObservableCollection();
}
private void InitializeObservableCollection()
{
foreach (var item in s.GetStudentList())
OBStudents.Add(item);
StudentsCollection = new CollectionViewSource { Source = OBStudents };
Itemlist = StudentsCollection.View;
DG_StudentsList.ItemsSource = Itemlist;
}
private void BTN_Exit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
private void CB_Filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!string.IsNullOrEmpty(sender.ToString()))
TB_SearchBox.IsEnabled = true;
else
TB_SearchBox.IsEnabled = false;
}
private void TB_SearchBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (CB_Filter.SelectedIndex == 0)
yourCostumFilter = new Predicate<object>(item => ((Student)item).Name.Contains(TB_SearchBox.Text));
else if (CB_Filter.SelectedIndex == 1)
yourCostumFilter = new Predicate<object>(item => ((Student)item).PhoneNum.Contains(TB_SearchBox.Text));
Itemlist.Filter = yourCostumFilter;
Itemlist.Refresh();
}
private void CB_BookName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox CB = (ComboBox)sender;
BookBorrowed borrowedBookDate,bbHolder =(BookBorrowed) CB.SelectedItem;
borrowedBookDate = s.GetBorrowedBookInfo((Student)DG_StudentsList.SelectedItem, bbHolder.BookName);
//ss = borrowedBookDate.BookLendDate.ToShortDateString();
/*DataGridTextColumn tc = new DataGridTextColumn();
tc.Header = "תאריך השאלה";
tc.Binding = new Binding("borrowedBookDate.BookLendDate, TargetNullValue=borrowedBookDate.BookLendDate");
DG_StudentsList.Columns.Add(tc);*/
}
}
public class Student
{
private readonly TextFileHandler TFH = TextFileHandler.Instance;
public List<string> Lines { get; private set; } = new List<string>();
private static readonly Lazy<Student> student = new Lazy<Student>(() => new Student());
public static Student Instance { get { return student.Value; } }
private Book b = Book.Instance;
private StudentsWindow SW;
public int Id { get; set; }
public string Name { get; set; }
public string PhoneNum { get; set; }
public List<BookBorrowed> BorrowedBooks { get; set; }
private Student() { }
private Student(int id, string name, string phoneNum, List<BookBorrowed> borrowedBooks)
{
Id = id;
Name = name;
PhoneNum = phoneNum;
BorrowedBooks = borrowedBooks;
}
public Student(string Name, string PhoneNum)
{
Id = GenerateID();
this.Name = Name;
this.PhoneNum = PhoneNum;
BorrowedBooks = new List<BookBorrowed>();
}
public Student(string Name, string PhoneNum, List<BookBorrowed> BorrowedBooks)
{
Id = GenerateID();
this.Name = Name;
this.PhoneNum = PhoneNum;
this.BorrowedBooks = BorrowedBooks;
}
public void AddStudent(Student newStudent)
{
SW = Application.Current.Windows.OfType<StudentsWindow>().First();
UpdateStudentsLinesList();
if (!TFH.CheckLineExistens($"שם:{newStudent.Name}", Paths.studentsFile) ||
!TFH.CheckLineExistens($"טלפון:{newStudent.PhoneNum}", Paths.studentsFile))
{
Lines.Add($"מ''ס:{GenerateID()}\n[");
Lines.Add($"שם:{newStudent.Name}");
Lines.Add($"טלפון:{newStudent.PhoneNum}");
Lines.Add($"ספרים מושאלים");
Lines.Add(#"{");
foreach (var book in newStudent.BorrowedBooks)
{
Lines.Add($"שם הספר:{book.BookName}");
Lines.Add($"תאריך השאלה:{DateTime.Now.ToShortDateString()}");
}
Lines.Add(#"}");
Lines.Add("]");
SW.WriteToConsole($"התלמיד {newStudent.Name} נוסף בהצלחה ");
}
else
{
SW.WriteToConsole($"התלמיד {newStudent.Name} כבר קיים במערכת ");
}
TFH.OverWriteFile(Lines, Paths.studentsFile);
}
public void AddStudentWithoutOuput(Student newStudent)
{
SW = Application.Current.Windows.OfType<StudentsWindow>().First();
UpdateStudentsLinesList();
if (!TFH.CheckLineExistens($"שם:{newStudent.Name}", Paths.studentsFile) ||
!TFH.CheckLineExistens($"טלפון:{newStudent.PhoneNum}", Paths.studentsFile))
{
Lines.Add($"מ''ס:{GenerateID()}\n[");
Lines.Add($"שם:{newStudent.Name}");
Lines.Add($"טלפון:{newStudent.PhoneNum}");
Lines.Add($"ספרים מושאלים");
Lines.Add(#"{");
foreach (var book in newStudent.BorrowedBooks)
{
Lines.Add($"שם הספר:{book.BookName}");
Lines.Add($"תאריך השאלה:{DateTime.Now.ToShortDateString()}");
}
Lines.Add(#"}");
Lines.Add("]");
}
TFH.OverWriteFile(Lines, Paths.studentsFile);
}
public void AddBookToStudent(Book newBook, Student student)
{
SW = Application.Current.Windows.OfType<StudentsWindow>().First();
bool bookExist = false;
student.BorrowedBooks.ForEach(bookName => {
if (bookName.Equals(newBook.BookName))
bookExist = true;
});
if (
!bookExist &
newBook.Quantity != 0)
{
student.BorrowedBooks.Add(new BookBorrowed(newBook.BookName));
StudentWithUpdatedBooks(student);
Book bookWithLowerQuantity = new Book(newBook);
bookWithLowerQuantity.Quantity--;
b.UpdateInfo(newBook, bookWithLowerQuantity);
SW.WriteToConsole($"הספר {newBook.BookName} נוסף בהצלחה לתלמיד {student.Name}");
SW.WriteToConsole($"כמות הספרים הנותרים מהספר {newBook.BookName}: {bookWithLowerQuantity.Quantity}");
}
else
{
if(bookExist)
SW.WriteToConsole($"הספר {newBook.BookName} כבר קיים אצל התלמיד {student.Name}");
else if(newBook.Quantity == 0)
SW.WriteToConsole($"אין עוד מספר זה בסיפרייה. כמות הספרים מהספר {newBook.BookName}: {newBook.Quantity--}");
}
}
public void DeleteStudent(Student student)
{
UpdateStudentsLinesList();
if (TFH.CheckLineExistens($"שם:{student.Name}", Paths.studentsFile) &
TFH.CheckLineExistens($"טלפון:{student.PhoneNum}", Paths.studentsFile))
{
if (student.BorrowedBooks.Count != 0)
{
List<Book> booksStudentHave = new List<Book>(), booksToReturn = new List<Book>();
student.BorrowedBooks.ForEach(bookName => {
booksStudentHave.Add(b.GetBookByInfo($"שם:{bookName}"));
});
booksStudentHave.ForEach(book => {
Book bHolder = new Book(book);
bHolder.Quantity += book.Quantity;
b.UpdateInfo(book,bHolder);
});
}
bool inMidName = false, inMidPhone = false, insindMide = false;
List<string> newList = new List<string>();
int idLine = new int(), currentline = 1;
foreach (var line in Lines)
{
if (line.Equals($"שם:{student.Name}"))
inMidName = true;
if (line.Equals($"טלפון:{student.PhoneNum}"))
inMidPhone = true;
if (inMidName & inMidPhone)
{
idLine = currentline - 4;
break;
}
currentline++;
}
int id = int.Parse(Lines[idLine].Substring(Lines[idLine].IndexOf(":")+1));
foreach (var line in Lines)
{
if (line.Equals($"מ''ס:{id}"))
insindMide = true;
if (insindMide)
{
if (line.Equals("]"))
insindMide = false;
}
else
newList.Add(line);
}
TFH.OverWriteFile(newList, Paths.studentsFile);
}
}
public void DeleteStudent(string name, string phoneNum)
{
UpdateStudentsLinesList();
if (TFH.CheckLineExistens($"שם:{name}", Paths.studentsFile) &
TFH.CheckLineExistens($"טלפון:{phoneNum}", Paths.studentsFile))
{
bool inMidName = false, inMidPhone = false, insindMide = false;
List<string> newList = new List<string>();
int idLine = new int(), currentline = 1;
foreach (var line in Lines)
{
if (line.Equals($"שם:{name}"))
inMidName = true;
if (line.Equals($"טלפון:{phoneNum}"))
inMidPhone = true;
if (inMidName & inMidPhone)
{
idLine = currentline - 4;
break;
}
currentline++;
}
int id = int.Parse(Lines[idLine].Substring(Lines[idLine].IndexOf(":") + 1));
foreach (var line in Lines)
{
if (line.Equals($"מ''ס:{id}"))
insindMide = true;
if (insindMide)
{
if (line.Equals("]"))
insindMide = false;
}
else
newList.Add(line);
}
TFH.OverWriteFile(newList, Paths.studentsFile);
}
}
public void StudentWithUpdatedBooks(Student student)
{
bool inMid = false;
List<string> updatedList = new List<string>();
foreach (var line in TFH.GetAllRawLines(Paths.studentsFile))
{
if (line.Equals($"מ''ס:{student.Id}"))
inMid = true;
if (inMid)
{
if (line.Equals("]"))
inMid = false;
}
else
updatedList.Add(line);
}
TFH.OverWriteFile(updatedList, Paths.studentsFile);
AddStudentWithoutOuput(student);
}
public void UpdateInfo(Student student,Student updatedStudent)
{
bool inMid = false;
List<string> updatedList = new List<string>();
foreach (var line in TFH.GetAllRawLines(Paths.studentsFile))
{
if (line.Equals($"מ''ס:{student.Id}"))
inMid = true;
if (inMid)
{
if (line.Equals("]"))
inMid = false;
}
else
updatedList.Add(line);
}
TFH.OverWriteFile(updatedList,Paths.studentsFile);
AddStudentWithoutOuput(updatedStudent);
}
private int GenerateID()
{
int newID = 0;
foreach (string line in TFH.GetAllRawLines(Paths.studentsFile))
{
if (line.Contains("מ''ס:"))
newID++;
}
return newID;
}
public List<string> GetNewStudent(Student student)
{
UpdateStudentsLinesList();
List<string> newLines = new List<string>();
if (!TFH.CheckLineExistens($"שם:{student.Name}", Paths.studentsFile) &
!TFH.CheckLineExistens($"טלפון:{student.PhoneNum}", Paths.studentsFile))
{
Lines.Add($"מ''ס:{student.Id}\n[");
Lines.Add($"שם:{student.Name}");
Lines.Add($"טלפון:{student.PhoneNum}");
Lines.Add($"ספרים מושאלים");
Lines.Add(#"{");
foreach (var book in student.BorrowedBooks)
{
Lines.Add($"שם הספר:{book.BookName}");
Lines.Add($"תאריך השאלה:{DateTime.Now.ToShortDateString()}");
}
Lines.Add(#"}");
Lines.Add("]");
}
return newLines;
}
public List<Student> GetStudentList()
{
List<Student> newList = new List<Student>();
foreach (var line in TFH.GetAllRawLines(Paths.studentsFile))
{
if (line.Contains("מ''ס"))
newList.Add(GetStudentByInfo(line));
}
return newList;
}
public Student GetStudentByInfo(string info)
{
string name = null, phoneNum = null,BB_name = null;
int id = new int();
DateTime BB_lent;
List<BookBorrowed> borrowedBooks = new List<BookBorrowed>();
bool inMid = false, inMidBooks = false, insideBook = false;
if (info.Contains("מ''ס"))
{
foreach (var line in TFH.GetAllRawLines(Paths.studentsFile))
{
if (line.Equals(info))
{
inMid = true;
id = int.Parse(line.Substring(line.IndexOf(":") + 1));
}
if (inMid)
{
if (line.Equals("]"))
break;
else if (line.Contains("שם:"))
name = line.Substring(line.IndexOf(":") + 1);
else if (line.Contains("טלפון:"))
phoneNum = line.Substring(line.IndexOf(":") + 1);
else if (line.Equals("{"))
{
inMidBooks = true;
continue;
}
else if (line.Equals("}"))
inMidBooks = false;
if (inMidBooks)
{
if (line.Contains("שם הספר:"))
{
BB_name = line.Substring(line.IndexOf(":") + 1);
insideBook = true;
continue;
}
if (insideBook)
{
BB_lent = DateTime.Parse(line.Substring(line.IndexOf(":")+1));
borrowedBooks.Add(new BookBorrowed(BB_name,BB_lent));
insideBook = false;
}
}
}
}
return new Student(id, name, phoneNum, borrowedBooks);
}
return null;
}
public void UpdateStudentsLinesList() { Lines = TFH.GetAllRawLines(Paths.studentsFile); }
public BookBorrowed GetBorrowedBookInfo(Student student,string borrowedBookName)
{
Student currentStudent = GetStudentByInfo($"מ''ס:{student.Id}");
foreach (var book in currentStudent.BorrowedBooks)
{
if (book.BookName.Equals(borrowedBookName))
return new BookBorrowed(book.BookName, book.BookLendDate);
}
return null;
}
}
public class BookBorrowed
{
public string BookName { get; set; }
public DateTime BookLendDate { get; set; }
public BookBorrowed(string BookName)
{
this.BookName = BookName;
this.BookLendDate = DateTime.Now;
}
public BookBorrowed(string BookName, DateTime BookLendDate)
{
this.BookName = BookName;
this.BookLendDate = BookLendDate;
}
}
No, you can't bind to a local variable. First of all, there is a local scope, a instance scope and a class scope. A local variable only lives in a local scope e.g. the block of an if-statement or a method body. As soon the instruction pointer leaves this scope the variable does no longer exist. You may mean an instance variable i.e. field, which lives as long as the object instance is living. Class variables would be static fields, variables that don't belong to the class instance, but the class itself.
Anyway, you can only bind to public properties. Microsoft Docs: Binding Source Types
If you have a public property, then you can also bind a column to it.
A common CLR property would also work. But in controls it is recommended to implement properties that serve as a binding source as DependencyProperty.
Dependency properties overview, Data binding overview in WPF
MainWindow.xaml.cs
partial class MainWindow : Window
{
public static readonly DependencyProperty BorrowedBookDateProperty = DependencyProperty.Register(
"BorrowedBookDate",
typeof(DateTime),
typeof(MainWindow),
new PropertyMetadata(default(DateTime)));
public DateTime TextValue
{
get => (DateTime) GetValue(MainWindow.BorrowedBookDateProperty);
set => SetValue(MainWindow.BorrowedBookDateProperty, value);
}
public MainWindow()
{
this.BorrowedBook = DateTime.Now;
}
}
MainWindow.xaml
<Window>
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Header="Borrowed Book Date"
Binding="{Binding RelativeSource={RelativeSource AncestorType=main:MainWindow}, Path=BorrowedBookDate}" />
</DataGrid.Columns>
</DataGrid>
</Window>
I am working on windows form application. I created user control which has datagridview control. I added dynamically 10 user control in a panel(which is in main form) which has "Observed(sec)" column in common. In this column user will enter values.And click on save button. All the values will get saved in text file.
My question is : I added everytime a new user control in a panel. Then how to get values from Observed column to save button?
Main form code
private void addUserContol()
{
string[] lines = File.ReadAllLines(filename);
string[] newline;
string[] splitLine;
try
{
int i = 0;
string lineText;
for (i = 0; i < lines.Length; )
{
uc_protectionTbl1 objUC = new uc_protectionTbl1(); //user control object is created here
uc_groupLbl objGrouplbl = new uc_groupLbl();
uc_testResult result = new uc_testResult();
uc_performResult objperform = new uc_performResult();
var wordCount = new Dictionary<string, int>();
lineText = lines[i++];
if (lineText != "")
{
if (lineText.Contains("Title"))
{
splitLine = lineText.Split('=');
lbl_title.Text = splitLine[1];
}
if (lineText.Contains("GroupLabel"))
{
splitLine = lineText.Split('=');
objGrouplbl.grouplblvalue = splitLine[1];
panelUC.Controls.Add(objGrouplbl);
}
if (lineText.Contains("Performance Test"))
{
panelUC.Controls.Add(objperform);
}
if (lineText.Contains("Result"))
{
splitLine = lineText.Split('=');
result.addTest = splitLine[1];
panelUC.Controls.Add(result);
}
if (lineText.Contains("TestType"))
{
splitLine = lineText.Split('=');
objUC.testType = splitLine[1];
lineText = lines[i++];
if (lineText.Contains("Heading"))
{
string[] delimiter = { "=", "||" };
splitLine = lineText.Split(delimiter, StringSplitOptions.None);
newline = splitLine.Skip(1).ToArray();
objUC.numColumn = newline.Count();
objUC.columnheading = newline;
}
while (i < lines.Length)
{
lineText = lines[i++];
if (lineText != "")
{
if (lineText.Contains("Value"))
{
string[] delimiter = { "=", "||" };
wordCount.Add(lineText, 1);
objUC.numRow = wordCount.Values.Count();
string[][] arrayofarray = wordCount.Select(x => (x.Key.Split(delimiter, StringSplitOptions.None)).Skip(1).ToArray()).ToArray();
objUC.rowValues = arrayofarray;
}
else
{
panelUC.Controls.Add(objUC); //here I added user control in panel
i = i - 1;
break;
}
}
}
}
}
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
private void SavetoolStripMenuItem1_Click(object sender, EventArgs e)
{
//Here I want all the values from observed(Sec) column
}
}
Code for user Control
public partial class uc_protectionTbl1 : UserControl
{
public string testType { get; set; }
public int numRow { get; set; }
public int numColumn { get; set; }
public string[] columnheading { get; set; }
public string[][] rowValues { get; set; }
public uc_protectionTbl1()
{
InitializeComponent();
}
private void uc_ProtectionTbl1_Load(object sender, EventArgs e)
{
designDT();
}
public DataTable uc_dt = new DataTable();
private void designDT()
{
try
{
foreach (var column in columnheading)
{
uc_dt.Columns.Add(new DataColumn(column.ToString()));
}
foreach (var row in rowValues)
{
uc_dt.Rows.Add(row);
}
dgv_uc.DataSource = uc_dt;
dgv_uc.Columns.Cast<DataGridViewColumn>().ToList().
ForEach(f => f.SortMode = DataGridViewColumnSortMode.NotSortable);
lbl_testType.Text = testType;
DataGridViewTextBoxColumn obs = new DataGridViewTextBoxColumn(); //Here I added textbox column
obs.HeaderText = "Observed(Sec)";
obs.Name = "Obs";
obs.ReadOnly = false;
this.dgv_uc.Columns.Add(obs);
var button = new DataGridViewButtonColumn();
button.Name = "TestButton";
button.HeaderText = "Test_Button";
button.Text = "Test";
button.UseColumnTextForButtonValue = true;
this.dgv_uc.Columns.Add(button);
sizeDGV(dgv_uc);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Please help me to resolve this issue. I am new in developement. From last 15 days searched google but not getting proper solution. Thanks in advance.
namespace Calendar
{
public partial class MainCalendar : Form
{
private JArray items;
private List<String> AMList = new List<String>();
private List<String> PMList = new List<String>();
private List<String> accessToCalendarFilepath = new List<String>();
private List<CalendarModel> people;
private List<List<CalendarModel>> managers = new List<List<CalendarModel>>();
private List<String> userSelection = new List<String>();
private bool authorizedAccess = false;
private String javaScriptFileContainingJSONObject = "";
public MainCalendar()
{
InitializeComponent();
var locationInformation = System.Environment.CurrentDirectory + Path.DirectorySeparatorChar + "location.json";
using (StreamReader file = File.OpenText(locationInformation))
using (JsonTextReader reader = new JsonTextReader(file))
{
JArray o = (JArray)JToken.ReadFrom(reader);
items = o;
}
foreach (var item in items.Children())
{
var itemProperties = item.Children<JProperty>();
// you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "name");
var myElementValue = myElement.Value; ////This is a JValue type
if(myElementValue.ToString().Contains("AM"))
{
AMList.Add(myElementValue.ToString());
}
if (myElementValue.ToString().Contains("PM"))
{
PMList.Add(myElementValue.ToString());
}
}
mondayAM.DataSource = AMList.ToArray();
tuesdayAM.DataSource = AMList.ToArray();
wednesdayAM.DataSource = AMList.ToArray();
thursdayAM.DataSource = AMList.ToArray();
fridayAM.DataSource = AMList.ToArray();
mondayPM.DataSource = PMList.ToArray();
tuesdayPM.DataSource = PMList.ToArray();
wednesdayPM.DataSource = PMList.ToArray();
thursdayPM.DataSource = PMList.ToArray();
fridayPM.DataSource = PMList.ToArray();
loadAccessControl("accesscontrol.json");
dateTimePicker1.AlwaysChooseMonday(dateTimePicker1.Value);
String dateSelected = dateTimePicker1.Value.ToShortDateString();
findManagerForSelectedDate(dateSelected);
}
public void loadAccessControl(String fileName)
{
var accessControlInformation = Environment.CurrentDirectory + Path.DirectorySeparatorChar + fileName;
List<AccessControl> accounts = JsonConvert.DeserializeObject<List<AccessControl>>(File.ReadAllText(accessControlInformation));
foreach (AccessControl account in accounts)
{
Console.WriteLine(account.accountName);
if (account.accountName.ToLower().Contains(Environment.UserName.ToLower()))
{
foreach (CalendarFile file in account.files)
{
// Console.WriteLine(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "content" + Path.DirectorySeparatorChar + file.Filename);
accessToCalendarFilepath.Add(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "content" + Path.DirectorySeparatorChar + file.Filename);
}
break;
}
}
contentsOfFile();
}
private void contentsOfFile()
{
String line;
foreach(var file in accessToCalendarFilepath)
{
StreamReader contentsOfJSONFile = new StreamReader(file);
while((line = contentsOfJSONFile.ReadLine()) != null)
{
if(line.Contains("var "))
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + "[";
}
else if(line.Contains("];"))
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + "]";
}
else
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + line;
}
}
people = JsonConvert.DeserializeObject<List<CalendarModel>>((string)javaScriptFileContainingJSONObject);
managers.Add(people);
javaScriptFileContainingJSONObject = "";
}
}
private void findManagerForSelectedDate(String dateSelected)
{
dateSelected = dateTimePicker1.Value.ToShortDateString();
List<String> managerNames = new List<String>();
foreach(var item in managers)
{
foreach (var subitem in item)
{
CalendarModel c = subitem;
Console.WriteLine(c.date);
c.name = new CultureInfo("en-US", false).TextInfo.ToTitleCase(c.name);
if (userSelection.Count > 0)
{
foreach (var addedUser in userSelection.ToArray())
{
if (!addedUser.Contains(c.name))
{
userSelection.Add(c.name); // CRASHING HERE
//{"Exception of type 'System.OutOfMemoryException' was thrown."}
}
}
}
else
{
userSelection.Add(c.name);
}
}
}
Console.WriteLine();
}
I keep running out of memory.
The CalendarModel class:
namespace Calendar
{
class CalendarModel
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("date")]
public string date { get; set; }
[JsonProperty("title")]
public string title { get; set; }
[JsonProperty("mondayAM")]
public string mondayAM { get; set; }
[JsonProperty("mondayPM")]
public string mondayPM { get; set; }
[JsonProperty("tuesdayAM")]
public string tuesdayAM { get; set; }
[JsonProperty("tuesdayPM")]
public string tuesdayPM { get; set; }
[JsonProperty("wednesdayAM")]
public string wednesdayAM { get; set; }
[JsonProperty("wednesdayPM")]
public string wednesdayPM { get; set; }
[JsonProperty("thursdayAM")]
public string thursdayAM { get; set; }
[JsonProperty("thursdayPM")]
public string thursdayPM { get; set; }
[JsonProperty("fridayAM")]
public string fridayAM { get; set; }
[JsonProperty("fridayPM")]
public string fridayPM { get; set; }
[JsonProperty("saturdayAM")]
public string saturdayAM { get; set; }
[JsonProperty("saturdayPM")]
public string saturdayPM { get; set; }
}
}
I keep crashing at
userSelection.Add(c.name)
Take a close look at what you are doing
foreach (var addedUser in userSelection.ToArray())
{
if (!addedUser.Contains(c.name))
{
userSelection.Add(c.name);
}
}
You are adding to userSelection in the userSelection loop
The test is on !addedUser.Contains
You should not even be able to do that but I think the ToArrray() is letting it happen
So you add Sally
Then then Mark
Then you add Mark again because in the loop Mark != Sally
You are not using List<String> managerNames = new List<String>();
private void findManagerForSelectedDate(String dateSelected)
{
dateSelected = dateTimePicker1.Value.ToShortDateString();
You pass in dateSelected, then overright with dateTimePicker1, and then you don't even use it
Most of you code makes very little sense to me
I need to split values from two columns into a datagridview.
You can see a screenshot of my values here:
I need to split match and result columns to have a column for every value.
This is my code:
Class:
using System;
using System.Collections.Generic;
namespace bexscraping
{
public class Bet
{
public string Match { get; set; }
public string Result { get; set; }
public List<string> Odds { get; set; }
public string Date { get; set; }
public Bet()
{
Odds = new List<string>();
}
public override string ToString()
{
String MatchInfo = String.Format("{0}: {1} -> {2}", Date, Match, Result);
String OddsInfo = String.Empty;
foreach (string d in Odds)
OddsInfo += " | " + d;
return MatchInfo + "\n" + OddsInfo;
}
}
}
form1:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using HtmlAgilityPack;
namespace bexscraping
{
public partial class Form1 : Form
{
private List<Bet> Bets;
private Bet SelectedBet { get; set; }
public Form1()
{
InitializeComponent();
dataGridView1.SelectionChanged += DataGridView1_SelectionChanged;
}
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0) {
SelectedBet = (Bet)dataGridView1.SelectedRows[0].DataBoundItem;
if (SelectedBet.Odds.Count > 0) {
textBox1.Text = SelectedBet.Odds[0].ToString();
textBox2.Text = SelectedBet.Odds[1].ToString();
textBox3.Text = SelectedBet.Odds[2].ToString();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
LoadInfo();
if (Bets.Count > 0)
{
SelectedBet = Bets[0];
dataGridView1.DataSource = Bets;
if (SelectedBet.Odds.Count > 0)
{
textBox1.Text = SelectedBet.Odds[0].ToString();
textBox2.Text = SelectedBet.Odds[1].ToString();
textBox3.Text = SelectedBet.Odds[2].ToString();
}
}
}
private void LoadInfo()
{
string url = "http://www.betexplorer.com/soccer/australia/northern-nsw/results/";
HtmlWeb web = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load(url);
Bets = new List<Bet>();
// Lettura delle righe
var Rows = doc.DocumentNode.SelectNodes("//tr");
foreach (HtmlNode row in Rows)
{
if (!row.GetAttributeValue("class", "").Contains("rtitle"))
{
if (string.IsNullOrEmpty(row.InnerText))
continue;
Bet rowBet = new Bet();
foreach (HtmlNode node in row.ChildNodes)
{
string data_odd = node.GetAttributeValue("data-odd", "");
if (string.IsNullOrEmpty(data_odd))
{
if (node.GetAttributeValue("class", "").Contains(("first-cell")))
rowBet.Match = node.InnerText.Trim();
var matchTeam = rowBet.Match.Split("-", StringSplitOptions.RemoveEmptyEntries);
rowBet.Home = matchTeam[0];
rowBet.Host = matchTeam[1];
if (node.GetAttributeValue("class", "").Contains(("result")))
rowBet.Result = node.InnerText.Trim();
var matchPoints = rowBet.Result.Split(":", StringSplitOptions.RemoveEmptyEntries);
rowBet.HomePoints = int.Parse(matchPoints[0];
rowBet.HostPoints = int.Parse(matchPoints[1];
if (node.GetAttributeValue("class", "").Contains(("last-cell")))
rowBet.Date = node.InnerText.Trim();
}
else
{
rowBet.Odds.Add(data_odd);
}
}
if (!string.IsNullOrEmpty(rowBet.Match))
Bets.Add(rowBet);
}
}
}
}
}
I hope you can help me. Thanks!
Ok after I try it this is working solution for me.
Probably its diferent namespace but all components have same name.
Form1 class
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using HtmlAgilityPack;
namespace Test
{
public partial class Form1 : Form
{
private List<Bet> Bets;
public Form1()
{
InitializeComponent();
Form1_Load_1();
dataGridView1.SelectionChanged += DataGridView1_SelectionChanged;
}
private Bet SelectedBet { get; set; }
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
SelectedBet = (Bet) dataGridView1.SelectedRows[0].DataBoundItem;
if (SelectedBet.Odds.Count > 0)
{
textBox1.Text = SelectedBet.Odds[0];
textBox2.Text = SelectedBet.Odds[1];
textBox3.Text = SelectedBet.Odds[2];
}
}
}
private void LoadInfo()
{
var url = "http://www.betexplorer.com/soccer/australia/northern-nsw/results/";
var web = new HtmlWeb();
var doc = web.Load(url);
Bets = new List<Bet>();
// Lettura delle righe
var Rows = doc.DocumentNode.SelectNodes("//tr");
foreach (var row in Rows)
{
if (!row.GetAttributeValue("class", "").Contains("rtitle"))
{
if (string.IsNullOrEmpty(row.InnerText))
continue;
var rowBet = new Bet();
foreach (var node in row.ChildNodes)
{
var data_odd = node.GetAttributeValue("data-odd", "");
if (string.IsNullOrEmpty(data_odd))
{
if (node.GetAttributeValue("class", "").Contains("first-cell"))
{
rowBet.Match = node.InnerText.Trim();
var matchTeam = rowBet.Match.Split(new[] {'-'}, StringSplitOptions.RemoveEmptyEntries);
rowBet.Home = matchTeam[0];
rowBet.Host = matchTeam[1];
}
if (node.GetAttributeValue("class", "").Contains("result"))
{
rowBet.Result = node.InnerText.Trim();
var matchPoints = rowBet.Result.Split(new[] {':'}, StringSplitOptions.RemoveEmptyEntries);
int help;
if (int.TryParse(matchPoints[0], out help))
{
rowBet.HomePoints = help;
}
if (matchPoints.Length == 2 && int.TryParse(matchPoints[1], out help))
{
rowBet.HostPoints = help;
}
}
if (node.GetAttributeValue("class", "").Contains("last-cell"))
rowBet.Date = node.InnerText.Trim();
}
else
{
rowBet.Odds.Add(data_odd);
}
}
if (!string.IsNullOrEmpty(rowBet.Match))
Bets.Add(rowBet);
}
}
}
private void Form1_Load_1()
{
LoadInfo();
if (Bets.Count > 0)
{
SelectedBet = Bets[0];
dataGridView1.DataSource = Bets;
if (SelectedBet.Odds.Count > 0)
{
textBox1.Text = SelectedBet.Odds[0];
textBox2.Text = SelectedBet.Odds[1];
textBox3.Text = SelectedBet.Odds[2];
}
}
}
}
}
Bets class
using System;
using System.Collections.Generic;
namespace Test
{
class Bet
{
public string Match { get; set; }
public string Result { get; set; }
public List<string> Odds { get; set; }
public string Date { get; set; }
public string Home { get; set; }
public string Host { get; set; }
public int HomePoints { get; set; }
public int HostPoints { get; set; }
public Bet()
{
Odds = new List<string>();
}
public override string ToString()
{
String MatchInfo = String.Format("{0}: {1} -> {2}", Date, Match, Result);
String OddsInfo = String.Empty;
foreach (string d in Odds)
OddsInfo += " | " + d;
return MatchInfo + "\n" + OddsInfo;
}
}
}
I'm stuck with following XML problem.
This is my XML file:
<POIs lastUsedId="9000010">
<POI id="9000010" name="München"><Latitude>48.139126</Latitude><Longitude>11.5801863</Longitude>
<Address>muenchen</Address><PhotoDescription>Hofbräuhaus</PhotoDescription>
<Photos directory="_x002F_pics"><PhotoFile>pic4poi_9000010-01.jpg</PhotoFile>
<PhotoFile>pic4poi_9000010-02.jpg</PhotoFile><PhotoFile>pic4poi_9000010-03.jpg</PhotoFile>
<PhotoFile>pic4poi_9000010-04.jpg</PhotoFile></Photos>
<InformationFile>infos\info4poi_9000010.txt</InformationFile></POI>
</POIs>
And here is my code to read the file:
XDocument doc = XDocument.Load(s);
lastID = Int32.Parse(doc.Root.Attribute("lastUsedId").Value.ToString());
CultureInfo cultureInfo = new CultureInfo("en-GB");
var pois = from res in doc.Descendants("POI")
select new
{
id = Int32.Parse(res.Attribute("id").Value.ToString()),
name = res.Attribute("name").Value.ToString(),
latitude = Double.Parse(res.Element("Latitude").Value, cultureInfo),
longitude = Double.Parse(res.Element("Longitude").Value, cultureInfo),
address = res.Element("Address").Value.ToString(),
photoDesc = res.Element("PhotoDescription").Value.ToString(),
photoDir = XmlConvert.DecodeName(res.Element("Photos").Attribute("directory").Value.ToString()),
photoFiles = from a in doc.Descendants("Photos")
select new
{
photo = a.Element("PhotoFile").Value.ToString()
},
info = res.Element("InformationFile").Value.ToString()
};
foreach (var poi in pois)
{
IEnumerable<string> pF = (poi.photoFiles as IEnumerable<string>);
List<string> photoFiles = null;
if(pF != null)
photoFiles = pF.ToList<string>();
AddPushpin(poi.id, poi.name, poi.latitude, poi.longitude, poi.address, poi.photoDesc, poi.photoDir, photoFiles, poi.info);
};
I'm unsure about the part with the PhotoFiles because I get an unknown Object error when I try to read the Pushpin.
This what my Pushpin looks like:
public class MyPushpin : Pushpin
{
public int ID { get; set; }
public string Address { get; set; }
public string PhotoDesc { get; set; }
public string PhotoDir { get; set; }
public List<string> PhotoFiles { get; set; }
public MyPushpin() { }
public MyPushpin(int id, string name, double latitude, double longitude, string address, string photoDesc, string photoDir, List<string> photoFiles, string info)
{
Location loc = new Location(latitude, longitude);
this.ID = id;
this.Location = loc;
this.Name = name;
this.Address = address;
this.PhotoDesc = photoDesc;
this.PhotoDir = photoDir;
this.PhotoFiles = photoFiles;
this.Tag = info;
}
public void Update(string name , string photoDesc, List<string> photoFiles, string info)
{
this.Name = name;
this.PhotoDesc = photoDesc;
this.PhotoFiles = photoFiles;
this.Tag = info;
}
public override string ToString()
{
return String.Format("{0} - {1}", this.ID, this.Location, this.Address, this.PhotoDesc, this.PhotoDir, this.Tag);
}
And that's the code how I would like to use the file info in the custom Pushpin:
public partial class Gallery : ChildWindow
{
List<string> pics = null;
public Gallery(MyPushpin currentPin)
{
InitializeComponent();
pics = currentPin.PhotoFiles;
Loaded += (a, b) => {
LoadImages();
};
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
Close();
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
Close();
}
private void LoadImages()
{
List<Picture> coll = new List<Picture>();
pics.ForEach(delegate(String url)
{
coll.Add(AddPicture("url"));
});
//coll.Add(AddPicture("/pics/pic4poi_9000010-01.jpg"));
//coll.Add(AddPicture("/pics/pic4poi_9000010-02.jpg"));
//coll.Add(AddPicture("/pics/pic4poi_9000010-03.jpg"));
//coll.Add(AddPicture("/pics/pic4poi_9000010-04.jpg"));
Preview.Source = new BitmapImage(
new Uri(
"/pics/pic4poi_9000010-01.jpg",
UriKind.Relative));
lbImage.ItemsSource = coll;
}
private Picture AddPicture(string path)
{
return new Picture
{
Href = new BitmapImage(
new Uri(
path,
UriKind.Relative))
};
}
private void lbImage_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Preview.Source = ((Picture)lbImage.SelectedItem).Href;
}
}
public class Picture
{
public ImageSource Href { get; set; }
THX for your time
Chau
Could you please describe the problem that you are having in more detail. Have you debugged into it, where does it fail, what is the exception? What do you expect it to do.
Off the top of my head, this code looks wrong:
photoFiles = from a in doc.Descendants("Photos")
select new
{
photo = a.Element("PhotoFile").Value.ToString()
},
Replace doc with res, because you want the child elements of the current element, not of the document. Also you can use Elements here instead of Descendants since they are direct children. Also since there are multiple photo files, try a SelectMany (from a ... from b ...):
photoFiles = from a in res.Elements("Photos")
from b in a.Elements("PhotoFile")
select new
{
photo = b.Value.ToString()
},