I create a custom grid control by extending the DataGridView in windows forms application. I use some custom functions for setting column readonly and some other functionalities. My current problem is when I use multiple controls in same form, it only reflects function execution output for the last control only. How make each control a separate instance of the user control?
public partial class dGridView : DataGridView
{
#region Member variables
DatagridViewCheckBoxHeaderCell chkHeader;
bool NeedToPopulateColumns = true;
public event DatagridViewCellButtonClickedHandler CellButtonClicked;
private int currentComboSelIndex;
#endregion
public dGridView()
{
InitializeComponent();
if (!DesignMode)
{
this.DoubleBuffered = true;
this.AutoGenerateColumns = false;
this.CellButtonClicked += new DatagridViewCellButtonClickedHandler(dGridView_CellButtonClicked);
}
}
#region Properties
/// <summary>
/// Gets or sets the datasource used to define columns.
/// </summary>
public object DesignDataSource
{
get;
set;
}
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool ExtendLastColumn
{
get;
set;
}
private List<string> AutoFilterColumnNames
{
get;
set;
}
private List<string> HiddenColumnsList
{
get;
set;
}
private List<string> ReadOnlyColumnsList
{
get;
set;
}
private List<string> ButtonColumnsList
{
get;
set;
}
private List<DGVSupportClass.ComboBoxColumns> ComboBoxColumnsList
{
get;
set;
}
private List<CustomCaptions> customCaptionList
{
get;
set;
}
#endregion
#region Methods
#region Public Methods
public void AddFilterToColumns(List<string> columnNames)
{
if (columnNames.Count > 0)
{
this.AutoFilterColumnNames = columnNames;
}
}
public void HiddenColumns(List<string> columnNames)
{
if (columnNames.Count > 0)
{
this.HiddenColumnsList = columnNames;
HideColumnsInList(this.HiddenColumnsList);
}
}
public void ReadOnlyColumns(List<string> columnNames)
{
if (columnNames.Count > 0)
{
this.ReadOnlyColumnsList = columnNames;
ReadOnlyColumnsInList(this.ReadOnlyColumnsList);
}
}
public void ReadOnlyRow(int rowIndex)
{
if (this.DataSource == null)
{
return;
}
this.Rows[rowIndex].ReadOnly = true;
}
public void AddButtonToCells(List<string> columnNames)
{
this.ButtonColumnsList = columnNames;
NeedToPopulateColumns = true;
FindBindingDataObjectType();
}
public void AddComboBoxColumn(List<DGVSupportClass.ComboBoxColumns> comboBoxColumns)
{
this.ComboBoxColumnsList = comboBoxColumns;
NeedToPopulateColumns = true;
FindBindingDataObjectType();
}
public void SetCustomDataSourceToComboBoxCell(int colIndex, int rowIndex, object cboxDataSource, string displayMember, string valueMember)
{
if (this.Columns[colIndex].GetType() != typeof(DataGridViewComboBoxColumn))
{
throw new Exception(string.Format("Column [{0}] is not a DataGridViewComboBoxColumn", colIndex));
}
if (string.IsNullOrEmpty(displayMember) || string.IsNullOrEmpty(valueMember))
{
throw new Exception("Display and Value Member must be passed");
}
DataGridViewComboBoxCell combo = this[colIndex, rowIndex] as DataGridViewComboBoxCell;
combo.DataSource = cboxDataSource;
combo.DisplayMember = displayMember;
combo.ValueMember = valueMember;
}
public void SetCustomDataSourceToComboBoxCell(int colIndex, int rowIndex, string[] cboxDataSource)
{
if (this.Columns[colIndex].GetType() != typeof(DataGridViewComboBoxColumn))
{
throw new Exception(string.Format("Column [{0}] is not a DataGridViewComboBoxColumn", colIndex));
}
DataGridViewComboBoxCell combo = this[colIndex, rowIndex] as DataGridViewComboBoxCell;
combo.DataSource = cboxDataSource;
}
public void CustomColumnCaptions(List<CustomCaptions> newColumnCaptions)
{
if (newColumnCaptions == null || newColumnCaptions.GetType() == typeof(System.DBNull))
{
return;
}
if (this.customCaptionList != newColumnCaptions)
this.customCaptionList = newColumnCaptions;
foreach (CustomCaptions col in newColumnCaptions)
{
if (this.Columns[col.ColumnName] != null)
this.Columns[col.ColumnName].HeaderCell.Value = col.ColumnCaption;
}
}
public void SetCustomColumnCaption(string columnName, string newCaption)
{
if (this.Columns.Contains(columnName))
{
if (this.Columns[columnName] != null)
this.Columns[columnName].HeaderCell.Value = newCaption;
}
CustomCaptions cap = new CustomCaptions(columnName, newCaption);
if (!customCaptionList.Contains(cap))
{
customCaptionList.Add(cap);
}
}
#endregion
#region Private Methods
private void AddFilterToColumnsInList(List<string> columnNames)
{
if (this.DataSource == null || columnNames == null)
{
return;
}
foreach (DataGridViewColumn col in this.Columns)
{
if (col.GetType() == typeof(DataGridViewTextBoxColumn) && columnNames.Contains(col.Name))
col.HeaderCell = new
DataGridViewAutoFilter.DataGridViewAutoFilterColumnHeaderCell(col.HeaderCell);
}
}
private void HideColumnsInList(List<string> columnNames)
{
if (this.DataSource == null || columnNames == null)
{
return;
}
foreach (DataGridViewColumn col in this.Columns)
{
if (this.HiddenColumnsList.Contains(col.Name))
{
col.Visible = false;
}
}
}
/// <summary>
/// Finds the type of the binding data object.
/// </summary>
private void FindBindingDataObjectType()
{
this.SuspendLayout();
this.ScrollBars = ScrollBars.None;
if (NeedToPopulateColumns)
{
if (this.DataSource is System.Collections.IList && this.DataSource.GetType().IsGenericType)
{
PopulateDataGridColumnsFromICartItem();
}
else
{
PopulateDataGridColumnsFromDataView();
}
NeedToPopulateColumns = false;
if (this.customCaptionList != null && this.customCaptionList.GetType() != typeof(System.DBNull))
{
CustomColumnCaptions(this.customCaptionList);
}
}
this.ScrollBars = ScrollBars.Both;
this.ResumeLayout();
}
/// <summary>
/// Populates the DataGridView columns with controls according to the
/// DataType of each columns which it represents. e.g. when a boolean
/// value found, then a DataGridViewCheckBoxColumn will be added and
/// for datetime it will be ESCalendarColumn (a custom control).
/// </summary>
private void PopulateDataGridColumnsFromDataView()
{
bool isComboAdded = false;
DataTable dt = null;
if (null == this.DataSource)
{
return;
}
else
{
switch (this.DataSource.GetType().ToString())
{
case "System.Data.DataTable":
dt = (DataTable)this.DataSource;
break;
case "System.Data.DataView":
dt = ((DataView)this.DataSource).Table;
break;
case "System.Data.DataSet":
dt = ((DataSet)this.DataSource).Tables[0];
break;
case "System.Windows.Forms.BindingSource":
if (((BindingSource)this.DataSource).DataSource.GetType() == typeof(DataTable))
{
dt = (DataTable)((BindingSource)this.DataSource).DataSource;
}
break;
default:
return;
}
}
this.Columns.Clear();
foreach (DataColumn dc in dt.Columns)
{
if (ButtonColumnsList != null && ButtonColumnsList.Contains(dc.ColumnName))
{
DataGridViewButtonColumn dvButton = new DataGridViewButtonColumn();
dvButton.Name = dc.ColumnName;
dvButton.HeaderText = dc.ColumnName;
this.Columns.Add(dvButton);
this.Columns[dvButton.Name].DataPropertyName = dvButton.Name;
continue;
}
if (ComboBoxColumnsList != null && ComboBoxColumnsList.Count > 0)
{
foreach (DGVSupportClass.ComboBoxColumns tmpData in ComboBoxColumnsList)
{
if (tmpData.ColumnName == dc.ColumnName)
{
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.DataPropertyName = dc.ColumnName;
comboCol.Name = dc.ColumnName;
comboCol.HeaderText = dc.ColumnName;
comboCol.DataSource = tmpData.DataSource;
if (!string.IsNullOrEmpty(tmpData.Display))
{
comboCol.DisplayMember = tmpData.Display;
comboCol.ValueMember = tmpData.Value;
}
comboCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton;
comboCol.FlatStyle = FlatStyle.Standard;
this.Columns.Add(comboCol);
isComboAdded = true;
break;
}
}
}
if (isComboAdded)
{
isComboAdded = false;
continue;
}
switch (((DataColumn)dc).DataType.ToString())
{
case "System.String":
case "System.Int32":
case "System.Int64":
case "System.Decimal":
case "System.Guid":
this.Columns.Add(dc.ColumnName, dc.Caption);
this.Columns[dc.ColumnName].DataPropertyName = dc.ColumnName;
this.Columns[dc.ColumnName].SortMode = DataGridViewColumnSortMode.Automatic;
break;
case "System.Boolean":
DataGridViewCheckBoxColumn chkbox = new DataGridViewCheckBoxColumn();
chkHeader = new DatagridViewCheckBoxHeaderCell();
chkbox.HeaderCell = chkHeader;
chkbox.Name = "chkBox" + dc.ColumnName;
chkbox.HeaderText = dc.ColumnName;
chkHeader.OnCheckBoxClicked += new CheckBoxClickedHandler(chkHeader_OnCheckBoxClicked);
this.Columns.Add(chkbox);
this.Columns[chkbox.Name].DataPropertyName = dc.ColumnName;
this.Columns[chkbox.Name].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
this.Columns[chkbox.Name].SortMode = DataGridViewColumnSortMode.NotSortable;
break;
case "System.DateTime":
ESCalendarColumn calendarCol = new ESCalendarColumn();
calendarCol.Name = ((DataColumn)dc).ColumnName;
calendarCol.HeaderText = ((DataColumn)dc).Caption;
this.Columns.Add(calendarCol);
this.Columns[calendarCol.Name].DataPropertyName = calendarCol.Name;
this.Columns[calendarCol.Name].SortMode = DataGridViewColumnSortMode.Automatic;
break;
default:
if (((DataColumn)dc).DataType.IsEnum)
{
List<DGVSupportClass.EnumToComboClass> lstCbo = new List<DGVSupportClass.EnumToComboClass>();
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.DataPropertyName = ((DataColumn)dc).ColumnName;
comboCol.Name = ((DataColumn)dc).ColumnName;
comboCol.HeaderText = ((DataColumn)dc).Caption;
comboCol.DataSource = Enum.GetValues(dc.DataType);
comboCol.FlatStyle = FlatStyle.Standard;
if (((DataColumn)dc).ReadOnly) comboCol.ReadOnly = true;
this.Columns.Add(comboCol);
}
else
{
this.Columns.Add(dc.ColumnName, dc.Caption);
this.Columns[dc.ColumnName].DataPropertyName = dc.ColumnName;
this.Columns[dc.ColumnName].SortMode = DataGridViewColumnSortMode.Automatic;
}
break;
}
}
NeedToPopulateColumns = false;
AddFilterToColumnsInList(this.AutoFilterColumnNames);
HideColumnsInList(this.HiddenColumnsList);
// Extend the last column
if (this.ExtendLastColumn)
{
this.Columns[this.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
/// <summary>
/// Populates the DataGridView columns with controls according to the
/// DataType of each columns which it represents. e.g. when a boolean
/// value found, then a DataGridViewCheckBoxColumn will be added and
/// for datetime it will be ESCalendarColumn (a custom control).
/// </summary>
private void PopulateDataGridColumnsFromICartItem()
{
this.Columns.Clear();
System.Reflection.PropertyInfo[] propertyInfos = null;
bool isComboAdded = false;
if (this.DesignDataSource != null)
{
if (this.DesignDataSource != null && this.DesignDataSource is System.Collections.IList && this.DesignDataSource.GetType().IsGenericType)
{
if (((System.Collections.IList)this.DesignDataSource).Count > 0 && (((System.Collections.IList)this.DesignDataSource)[0]) != null)
{
propertyInfos = (((System.Collections.IList)this.DesignDataSource)[0]).GetType().GetProperties();
}
else
{
propertyInfos = this.DesignDataSource.GetType().GetProperties();
propertyInfos = propertyInfos[propertyInfos.Length - 1].PropertyType.GetProperties();
}
}
}
else
{
if (this.DataSource != null && this.DataSource is System.Collections.IList && this.DataSource.GetType().IsGenericType)
{
if (((System.Collections.IList)this.DataSource).Count > 0)
{
propertyInfos = (((System.Collections.IList)this.DataSource)[0]).GetType().GetProperties();
}
else
{
propertyInfos = this.DataSource.GetType().GetProperties();
propertyInfos = propertyInfos[propertyInfos.Length - 1].PropertyType.GetProperties();
}
}
}
if (propertyInfos != null)
{
foreach (var item in propertyInfos)
{
if (ComboBoxColumnsList != null && ComboBoxColumnsList.Count > 0)
{
foreach (DGVSupportClass.ComboBoxColumns tmpData in ComboBoxColumnsList)
{
if (tmpData.ColumnName == item.Name)
{
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.DataPropertyName = item.Name;
comboCol.Name = item.Name;
comboCol.HeaderText = item.Name;
comboCol.DataSource = tmpData.DataSource;
if (!string.IsNullOrEmpty(tmpData.Display))
{
comboCol.DisplayMember = tmpData.Display;
comboCol.ValueMember = tmpData.Value;
}
comboCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton;
comboCol.FlatStyle = FlatStyle.Standard;
this.Columns.Add(comboCol);
isComboAdded = true;
break;
}
}
}
if (isComboAdded)
{
isComboAdded = false;
continue;
}
if (ButtonColumnsList != null && ButtonColumnsList.Contains(item.Name))
{
DataGridViewButtonColumn dvButton = new DataGridViewButtonColumn();
dvButton.Name = item.Name;
dvButton.HeaderText = item.Name;
this.Columns.Add(dvButton);
this.Columns[dvButton.Name].DataPropertyName = dvButton.Name;
}
else
{
switch (item.PropertyType.ToString())
{
case "System.String":
case "System.Int32":
case "System.Int64":
case "System.Decimal":
case "System.Guid":
DataGridViewTextBoxColumn txtBox = new DataGridViewTextBoxColumn();
txtBox.Name = item.Name;
this.Columns.Add(txtBox);
this.Columns[item.Name].DataPropertyName = item.Name;
break;
case "System.Boolean":
DataGridViewCheckBoxColumn chkbox = new DataGridViewCheckBoxColumn();
chkHeader = new DatagridViewCheckBoxHeaderCell();
chkbox.HeaderCell = chkHeader;
chkbox.Name = "chkBox" + item.Name;
chkbox.HeaderText = item.Name;
chkHeader.OnCheckBoxClicked += new CheckBoxClickedHandler(chkHeader_OnCheckBoxClicked);
this.Columns.Add(chkbox);
this.Columns[chkbox.Name].DataPropertyName = item.Name;
this.Columns[chkbox.Name].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
this.Columns[chkbox.Name].SortMode = DataGridViewColumnSortMode.NotSortable;
break;
case "System.DateTime":
ESCalendarColumn calendarCol = new ESCalendarColumn();
calendarCol.Name = item.Name;
calendarCol.HeaderText = item.Name;
this.Columns.Add(calendarCol);
this.Columns[calendarCol.Name].DataPropertyName = calendarCol.Name;
break;
default:
if (item.PropertyType.IsEnum && item.PropertyType.IsPublic)
{
List<DGVSupportClass.EnumToComboClass> lstCbo = new List<DGVSupportClass.EnumToComboClass>();
foreach (System.Reflection.FieldInfo fInfo in item.PropertyType.GetFields(
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
{
lstCbo.Add(new DGVSupportClass.EnumToComboClass(fInfo.Name, fInfo.GetRawConstantValue().ToString()));
}
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.DataPropertyName = item.Name;
comboCol.Name = item.Name;
comboCol.HeaderText = item.Name;
comboCol.DataSource = lstCbo;
comboCol.DisplayMember = "Display";
comboCol.ValueMember = "Value";
comboCol.FlatStyle = FlatStyle.Standard;
this.Columns.Add(comboCol);
}
else if (!item.PropertyType.IsAbstract)
{
DataGridViewTextBoxColumn txtBoxDefault = new DataGridViewTextBoxColumn();
txtBoxDefault.Name = item.Name;
txtBoxDefault.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.Columns.Add(txtBoxDefault);
this.Columns[item.Name].DataPropertyName = item.Name;
}
break;
}
}
}
}
if (this.ExtendLastColumn)
{
this.Columns[this.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
AddFilterToColumnsInList(this.AutoFilterColumnNames);
HideColumnsInList(this.HiddenColumnsList);
}
#endregion
#endregion
#region Events
protected override void OnDataSourceChanged(EventArgs e)
{
if (this.DesignDataSource == null)
{
this.DesignDataSource = this.DataSource;
NeedToPopulateColumns = true;
}
FindBindingDataObjectType();
base.OnDataSourceChanged(e);
}
protected override void OnCellContentClick(DataGridViewCellEventArgs e)
{
if (this.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewButtonColumn))
{
DatagridViewCellButtonClickEventArgs dc = new DatagridViewCellButtonClickEventArgs(this.CurrentCell.Value.ToString(),
this.CurrentCell.Tag, this.CurrentCell.ColumnIndex, this.CurrentCell.RowIndex, this.CurrentCell.Value);
if (CellButtonClicked != null) { CellButtonClicked(this, dc); }
}
else if (this.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewComboBoxColumn))
{
this.CurrentCell = this[e.ColumnIndex, e.RowIndex];
this.BeginEdit(false);
ComboBox comboBox = this.EditingControl as ComboBox;
if (comboBox != null)
{
comboBox.DroppedDown = true;
}
}
base.OnCellContentClick(e);
}
protected override void OnCellClick(DataGridViewCellEventArgs e)
{
if (this.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewComboBoxColumn))
{
this.CurrentCell = this[e.ColumnIndex, e.RowIndex];
this.BeginEdit(false);
ComboBox comboBox = this.EditingControl as ComboBox;
if (comboBox != null)
{
comboBox.DroppedDown = true;
}
}
base.OnCellClick(e);
}
protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e)
{
base.OnDataBindingComplete(e);
}
protected override void OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
List<ColumnSettingsClass> LCss = new List<ColumnSettingsClass>();
foreach (DataGridViewColumn col in this.Columns)
{
if (!HiddenColumnsList.Contains(col.Name))
{
LCss.Add(new ColumnSettingsClass(col.Name, col.HeaderText, col.Width, col.Index, col.Visible));
}
}
ColumnSettings frmCs = new ColumnSettings(ref LCss);
frmCs.ShowDialog(this);
foreach (ColumnSettingsClass item in LCss)
{
if (this.Columns.Contains(item.ColumnName))
{
this.Columns[item.ColumnName].DisplayIndex = item.ColumnOrdinal;
this.Columns[item.ColumnName].Width = item.ColumnWidth;
this.Columns[item.ColumnName].Visible = item.Visibility;
}
}
}
base.OnColumnHeaderMouseClick(e);
}
protected override void OnCurrentCellDirtyStateChanged(EventArgs e)
{
base.OnCurrentCellDirtyStateChanged(e);
this.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is ComboBox)
{
ComboBox comboBox = e.Control as ComboBox;
comboBox.SelectedIndexChanged -= new EventHandler(LastColumnComboSelectionChanged);
comboBox.SelectedIndexChanged += new EventHandler(LastColumnComboSelectionChanged);
if (comboBox != null)
comboBox.DropDown += delegate(object s, EventArgs se) { ((ComboBox)s).BackColor = this.DefaultCellStyle.BackColor; };
}
base.OnEditingControlShowing(e);
}
private void LastColumnComboSelectionChanged(object sender, EventArgs e)
{
var currentcell = this.CurrentCellAddress;
var sendingCB = sender as DataGridViewComboBoxEditingControl;
if (sendingCB.EditingControlValueChanged)
{
DataGridViewTextBoxCell cel = (DataGridViewTextBoxCell)this.Rows[currentcell.Y].Cells[0];
cel.Value = sendingCB.EditingControlFormattedValue.ToString();
}
sendingCB.SelectedIndexChanged -= new EventHandler(LastColumnComboSelectionChanged);
}
#endregion
}
You can create different instances of the UserControl, I usually do so.
MyUserControl myUc MyUserControl = new ();
public MyUserControl CALLED= null;
private void FrmXXXXX_Load(object sender, EventArgs e)
{
MyUserControl uc = new MyUserControl ();
uc.VALUE = this.VALUE;
uc.CALLER = this;
uc.Parent = pnlMain;
uc.Dock = DockStyle.Fill;
}
This way you can create many different UserControl equal but different instances in memory and behavior
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'm attempting to make a google map using Xamarin forms, the pins displays correctly and zooms in onto the user. It displays the inital map when the page starts, but when moving or zooming the map doesn't change and becomes grids if you zoom in enough. I can see my pin on the grid and everything, but I would like the map to load along with the pin.
public partial class IssueMap2 : ContentPage
{
public UIIssueVM Issue { get; set; }
public GeoLocation Location { get; set; }
public bool AllowPinMovment { get; set; }
private ExtendedMap.ExtendedMap map;
public Xamarin.Forms.Maps.Position OrgIssueLocation { get; set; }
bool IsGettingLocation = false;
bool bMapCtrlReady = false;
IGeolocator Locator;
public IssueMap2(UIIssueVM Issue, GeoLocation location)
{
AllowPinMovment = false;
this.Issue = Issue;
this.Location = location;
Title = "Map";
OrgIssueLocation = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
Locator = CrossGeolocator.Current;
if (Locator.DesiredAccuracy != 100)
Locator.DesiredAccuracy = 100;
if (Device.RuntimePlatform != Device.WinPhone)
{
InitializeComponent();
map = new ExtendedMap.ExtendedMap()
{
IsShowingUser = true,
HeightRequest = 100,
WidthRequest = 960,
VerticalOptions = LayoutOptions.FillAndExpand
};
map.LongTap += OnMapLongTap;
map.Ready += MapCtrlReady;
slMap.Children.Add(map);
}
}
public void MapCtrlReady(object sender, EventArgs args)
{
bMapCtrlReady = true;
}
public void OnMapLongTap(object sender, ExtendedMap.TapEventArgs args)
{
if (AllowPinMovment == false)
return;
if (Issue == null)
return;
var pos = args.Position;
// Update Issue
Issue.Latitude = pos.Latitude;
Issue.Longitude = pos.Longitude;
Issue.Changed = true;
// Update Pin
map.Pins.Clear();
AddPin(pos, Issue.Title, Issue.Description);
}
protected void AddPin(Xamarin.Forms.Maps.Position pos, String Title, String Desc)
{
// MAP pin does not like it if labels are empty
if (Title.Length == 0)
Title = "-";
if (Desc.Length == 0)
Desc = "-";
var pin = new Pin
{
Type = PinType.Place,
Position = pos,
Label = Title,
Address = Desc
};
map.Pins.Add(pin);
}
protected override void OnAppearing()
{
if (Device.RuntimePlatform == Device.WinPhone)
{
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
if (Issue.IsNew == false)
{
var position = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
AddPin(position, Issue.Title, Issue.Description);
MoveToPinLocation();
}
else // Issue is new
{
// Move to main location
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromMiles(1)));
// Get current location for new item
OnGetLocation();
}
}
}
protected override async void OnDisappearing()
{
if (Locator.IsListening)
{
await Locator.StopListeningAsync();
}
// Map controller crashes sometimes if we are to quick with exiting
await Task.Delay(500);
while (bMapCtrlReady == false)
{
await Task.Delay(500);
}
}
void OnButtonCenter(object sender, EventArgs args)
{
MoveToPinLocation();
}
void MoveToPinLocation()
{
double KmDistace = 0.5;
if (Issue != null)
{
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude), Distance.FromKilometers(KmDistace)));
}
else
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromKilometers(KmDistace)));
}
void OnButtonMainLocation(object sender, EventArgs args)
{
double KmDistace = 0.5;
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromKilometers(KmDistace)));
}
void OnButtonGetLocation(object sender, EventArgs args)
{
OnGetLocation();
}
async void OnGetLocation()
{
if (IsGettingLocation == true)
return; // already getting location
try
{
if (Locator.IsListening == true)
{
await Locator.StopListeningAsync();
}
if (Locator.IsGeolocationAvailable == false)
{
lbPosText.Text = "GeoLocation is not available.";
this.ForceLayout();
return;
}
if (Locator.IsGeolocationEnabled == false)
{
lbPosText.Text = "GeoLocation is not enabled.";
this.ForceLayout();
return;
}
IsGettingLocation = true;
IsBusy = true;
slCommands.IsVisible = false;
aActIndicator.IsVisible = true;
aActIndicator.IsRunning = true;
lbPosText.Text = "Searching for GPS location...";
this.ForceLayout();
TimeSpan timeSpan = TimeSpan.FromTicks(120 * 1000);
var position = await Locator.GetPositionAsync(timeSpan);
// Update Issue Position
Issue.Latitude = position.Latitude;
Issue.Longitude = position.Longitude;
Issue.Changed = true;
// Update Pin Postion
var pos = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
map.Pins.Clear();
AddPin(pos, Issue.Title, Issue.Description);
UpdateGPSLocationText();
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
IsGettingLocation = false;
IsBusy = false;
slCommands.IsVisible = true;
this.ForceLayout();
// Center map around pin
MoveToPinLocation();
}
catch (Exception /*ex*/)
{
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
IsGettingLocation = false;
IsBusy = false;
slCommands.IsVisible = true;
lbPosText.Text = "Unable to find position!";
lbPosText.IsVisible = true;
this.ForceLayout();
}
}
void UpdateGPSLocationText()
{
String text = String.Format("{0} x {1}", Issue.Longitude, Issue.Latitude);
lbPosText.Text = text;
}
}
}
Android extended map renderer
[assembly: ExportRenderer(typeof(ExtendedMap.ExtendedMap), typeof(ExtendedMapRenderer))]
namespace ExtendedMap.Android
{
public class ExtendedMapRenderer : MapRenderer, IOnMapReadyCallback
{
private GoogleMap _map;
public ExtendedMapRenderer()
{
}
public ExtendedMapRenderer(IntPtr javaReference, JniHandleOwnership jniHandleOwnership)
{
int x = 0;
x++;
}
private void InvokeOnMapReadyBaseClassHack(GoogleMap googleMap)
{
System.Reflection.MethodInfo onMapReadyMethodInfo = null;
Type baseType = typeof(MapRenderer);
foreach (var currentMethod in baseType.GetMethods(System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.DeclaredOnly))
{
if (currentMethod.IsFinal && currentMethod.IsPrivate)
{
if (string.Equals(currentMethod.Name, "OnMapReady", StringComparison.Ordinal))
{
onMapReadyMethodInfo = currentMethod;
break;
}
if (currentMethod.Name.EndsWith(".OnMapReady", StringComparison.Ordinal))
{
onMapReadyMethodInfo = currentMethod;
break;
}
}
}
if (onMapReadyMethodInfo != null)
{
onMapReadyMethodInfo.Invoke(this, new[] { googleMap });
}
}
void IOnMapReadyCallback.OnMapReady(GoogleMap googleMap)
{
InvokeOnMapReadyBaseClassHack(googleMap);
_map = googleMap;
if (_map != null)
{
_map = googleMap;
this.NativeMap = googleMap;
_map.MapClick += googleMap_MapClick;
_map.MapLongClick += googleMap_MapLongClick;
((ExtendedMap)Element).OnReady();
}
}
protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
{
if (_map != null)
_map.MapClick -= googleMap_MapClick;
base.OnElementChanged(e);
if (Control != null)
((MapView)Control).GetMapAsync(this);
}
private void googleMap_MapClick(object sender, GoogleMap.MapClickEventArgs e)
{
((ExtendedMap)Element).OnTap(new Position(e.Point.Latitude, e.Point.Longitude));
}
private void googleMap_MapLongClick(object sender, GoogleMap.MapLongClickEventArgs e)
{
((ExtendedMap)Element).OnLongTap(new Position(e.Point.Latitude, e.Point.Longitude));
}
}
}
I would double check the Google Maps API key on the manifest of your application!
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzr3yCpVgSOXvTgri29nC6KqFbdO73QmoVQWEw" />
As well as your SHA-1 key of your keystore on the Google API Credential Dashboard.
i have an orderdetails page wherein customers can view their history page. And this is the url:
when i change the ID from 13 to lets say 14, it still shows the details on whats inside ID#14. What i want to happen is to have an error when customers try to change the localhost ID. Or to restrict the ID to be edited? Really dont have any idea on what to do. Encryption?
By the way here is the orderdetails code behind: (this is in user control)
public partial class ucCustomerOrder1 : System.Web.UI.UserControl
{
public bool CanIUpdateStatus;
public string TransactionNoText
{
get { return txtTransactionNo.Text; }
set { txtTransactionNo.Text = value; }
}
public bool IsAuthorizedToAddStatus
{
set { CanIUpdateStatus = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["IslandGasAdmin/ST"] == null)
{
txtTransactionNo.ReadOnly = true;
btnGo.Visible = false;
}
else
{
txtTransactionNo.ReadOnly = false;
btnGo.Visible = true;
}
if (txtTransactionNo.Text != string.Empty)
{
ShowOrderDetails(rblOrderDetails.SelectedValue, Convert.ToInt32(txtTransactionNo.Text));
}
else
{
rblOrderDetails.Visible = false;
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = false;
Panel4.Visible = false;
}
}
}
private void ShowOrderDetails(string PanelId, int OrderNo)
{
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = false;
Panel4.Visible = false;
rblOrderDetails.Visible = false;
if (IsOrderNoValid(OrderNo))
{
rblOrderDetails.Visible = true;
if (PanelId == "1")
{
ShoppingCart k = new ShoppingCart
{
Flag = OrderNo
};
DataTable dtCustomerDetails = k.GetOrderList();
if (dtCustomerDetails.Rows.Count > 0)
{
Panel1.Visible = true;
lblCustomerName.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerName"]);
lblCustomerPhoneNo.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerPhoneNo"]);
lblCustomerEmailID.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerEmailID"]);
lblTotalPrice.Text = String.Format("{0:#,000.00}",dtCustomerDetails.Rows[0]["TotalPrice"]);
lblTotalProducts.Text = Convert.ToString(dtCustomerDetails.Rows[0]["TotalProducts"]);
txtCustomerAddress.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerAddress"]);
lblPaymentMethod.Text = Convert.ToString(dtCustomerDetails.Rows[0]["PaymentMethod"]);
}
}
if (PanelId == "2")
{
Panel2.Visible = true;
ShoppingCart k = new ShoppingCart()
{
Flag = OrderNo
};
dlProducts.DataSource = k.GetTransactionDetails(); ;
dlProducts.DataBind();
}
if (PanelId == "3")
{
Panel3.Visible = true;
DropDownStatus.Visible = CanIUpdateStatus;
txtStatus.Visible = false;
//txtStatus.Visible = CanIUpdateStatus;
btnAdd.Visible = CanIUpdateStatus;
GetSetOrderStatus(0);
}
}
else
{
Panel4.Visible = true;
}
}
private bool IsOrderNoValid(int OrderNo)
{
ShoppingCart k = new ShoppingCart
{
Flag = OrderNo
};
DataTable dtCustomerDetails = k.GetOrderList();
if (dtCustomerDetails.Rows.Count > 0)
return true;
else
return false;
}
private void GetSetOrderStatus(int Flag)
{
ShoppingCart k = new ShoppingCart
{
OrderStatus = DropDownStatus.SelectedValue,
OrderNo = txtTransactionNo.Text,
Flag = Flag
};
DataTable dt = k.GetSetOrderStatus();
gvOrderStatus.DataSource = dt;
gvOrderStatus.DataBind();
//txtStatus.Text = string.Empty;
//DropDownStatus.SelectedValue = string.Empty;
}
please do help me, thank you
I am trying to access data store in ResultID from the following code:
public class ResultPanelEventArgs : EventArgs
{
private string stringResultId = string.Empty;
private int intRowIndex = -1;
private string stringAnalysisName = string.Empty;
private DateTime dateTimeAnalysisDateTime;
/// <summary>
/// Gets or sets the row index of selected result.
/// </summary>
public int RowIndex
{
get { return intRowIndex; }
set { intRowIndex = value; }
}
/// <summary>
/// Gets or sets the result id of selected result.
/// </summary>
public string ResultId
{
get { return stringResultId; }
set { stringResultId = value; }
}
/// <summary>
/// Gets or sets the date and time of the selected result.
/// </summary>
public DateTime AnalysisDateTime
{
get { return dateTimeAnalysisDateTime; }
set { dateTimeAnalysisDateTime = value; }
}
/// <summary>
/// Gets or sets the name of the sample as Analysis name.
/// </summary>
public string AnalysisName
{
get { return stringAnalysisName; }
set { stringAnalysisName = value; }
}
};
I have a method to pull the info:
private string GetResultID(object sender, ResultPanelEventArgs e)
{
string resultID = string.Empty;
resultID = e.ResultId.ToString();
return resultID;
}
but cannot seem to call that method (I get Argument errors). I am somewhat new to c# and have never worked with EventArgs so I don't even know if this is possible. Any advice on how to access the data stored here?
Per request here are three methods that appear to populate ResultId:
private ResultPanelEventArgs GetDataForTheGivenRowIndex(int intRowIndex)
{
ResultPanelEventArgs resultPanelEventArgs = new ResultPanelEventArgs();
resultPanelEventArgs.RowIndex = intRowIndex;
try
{
if (intRowIndex >= 0 && intRowIndex < dataGridViewResultView.Rows.Count)
{
object objectResultId = null;
if (dataGridViewResultView.Columns.Contains("ColumnResultId") == true)
{
objectResultId = dataGridViewResultView.Rows[intRowIndex].Cells["ColumnResultId"].Value;
}
else
{
objectResultId = dataGridViewResultView.Rows[intRowIndex].Tag;
}
if (objectResultId != null)
{
resultPanelEventArgs.ResultId = objectResultId.ToString();
}
object objectAnalysisName = null;
if (dataGridViewResultView.Columns.Contains("ColumnAnalysis") == true)
{
objectAnalysisName = dataGridViewResultView.Rows[intRowIndex].Cells["ColumnAnalysis"].Value;
}
else
{
objectAnalysisName = dataGridViewResultView.Rows[intRowIndex].Tag;
}
if (objectAnalysisName != null)
{
resultPanelEventArgs.AnalysisName = objectAnalysisName.ToString();
}
object objectAnalysisDateTime = null;
if (dataGridViewResultView.Columns.Contains("ColumnDate") == true)
{
objectAnalysisDateTime = dataGridViewResultView.Rows[intRowIndex].Cells["ColumnDate"].Value;
}
else
{
objectAnalysisDateTime = dataGridViewResultView.Rows[intRowIndex].Tag;
}
if (objectAnalysisDateTime != null)
{
resultPanelEventArgs.AnalysisDateTime =
Utilities.ConvertStringToDateTime(objectAnalysisDateTime.ToString());
}
}
}
catch
{
resultPanelEventArgs = null;
//Nothing to do
}
return resultPanelEventArgs;
}
and
private ResultPanelEventArgs GetDataForTheGivenResultID(string stringResultId)
{
ResultPanelEventArgs resultPanelEventArgs = null;
try
{
foreach (DataGridViewRow dataGridViewRow in dataGridViewResultView.Rows)
{
if (dataGridViewRow != null)
{
if (dataGridViewRow.Index >= 0)
{
if (dataGridViewRow.Cells["ColumnResultId"] != null)
{
if (dataGridViewRow.Cells["ColumnResultId"].Value.ToString() == stringResultId)
{
//Create the ResultPanelEventArgs
object objectResultId = dataGridViewRow.Cells["ColumnResultId"].Value;
object objectAnalysisName = dataGridViewRow.Cells["ColumnAnalysis"].Value;
object objectAnalysisDateTime = dataGridViewRow.Cells["ColumnDate"].Tag;
resultPanelEventArgs = new ResultPanelEventArgs();
if (objectResultId != null)
{
resultPanelEventArgs.RowIndex = dataGridViewRow.Index;
resultPanelEventArgs.ResultId = objectResultId.ToString();
resultPanelEventArgs.AnalysisName = objectAnalysisName.ToString();
resultPanelEventArgs.AnalysisDateTime = (DateTime)objectAnalysisDateTime;
}
dataGridViewRow.Selected = true;
break;
}
}
}
}
}
}
catch
{
resultPanelEventArgs = null;
//Nothing to do
}
return resultPanelEventArgs;
}
and
private void dataGridViewResultList_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
if (e.RowIndex >= 0)
{
this.result = this.GetResult(e.RowIndex);
ResultPanelEventArgs resultPanelEventArgs = new ResultPanelEventArgs();
resultPanelEventArgs.ResultId = this.result.Id.ToString();
resultPanelEventArgs.RowIndex = this.dataGridViewResultList.SelectedRows[0].Index;
if (this.DoubleClicked != null)
{
this.DoubleClicked(sender, resultPanelEventArgs);
}
this.DialogResult = DialogResult.OK;
}
}
catch (Exception ex)
{
UICommon.LogError(ex);
}
}
I assume this is an event handler. If you are using an event that uses the standard base class, but triggering it with the ResultPanelEventArgs, you will need to handle it with the base class EventArgs then cast them to the correct type.
private void HandleResultID(object sender, EventArgs args)
{
var e = (ResultPanelEventArgs) args;
var resultID = e.ResultId.ToString();
// Now do something with the ID. You cannot return it, because this is handling the click event.
}
Update: To subscribe to an event (add an event handler to an event):
this.DoubleClicked += new EventHandler(HandleResultID);
I am binding the data grid view by using the following linq to entity framework query by using the following code..
private void EquipmentFinder_Load(object sender, EventArgs e)
{
SetupCategories();
productgridview.RowTemplate.Height = 130;
var products = from prods in axe.product1
select new
{
productid = prods.product_Id, //0
productnam = prods.product_Name, //1
productimage = prods.product_Image, //2
productprice = prods.product_Price,//3
productdescr = prods.product_Description, //4
};
productbindingsource.DataSource = products;
productgridview.DataSource = productbindingsource;
productgridview.Columns[0].Visible = false;
productgridview.Columns[4].Visible = false;
}
I have got the columns product id , product image ,product name ,product desription,product price..
i have made some of the columns are not visible for the purpose of client ..
now i want to sort the columns by clicking on the column header ....
Note: here the product.image is stored as byte of arrays in database ....
i dont know how to compare the bytes and sorting like that....
would any one pls help on this one......
many thanks...
MODIFIED CODE:
private void productgridview_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewColumn newcolumn = productgridview.Columns.GetColumnCount(DataGridViewElementStates.Selected) == 1 ? productgridview.SelectedColumns[0] : null;
DataGridViewColumn oldColumn = productgridview.SortedColumn;
ListSortDirection direction;
if (oldColumn != null)
{
// Sort the same column again, reversing the SortOrder.
if (oldColumn == newcolumn &&
productgridview.SortOrder == SortOrder.Ascending)
{
direction = ListSortDirection.Descending;
}
else
{
// Sort a new column and remove the old SortGlyph.
direction = ListSortDirection.Ascending;
oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
}
}
else
{
direction = ListSortDirection.Ascending;
}
productgridview.Sort(newcolumn, direction);
newcolumn.HeaderCell.SortGlyphDirection =
direction == ListSortDirection.Ascending ?
SortOrder.Ascending : SortOrder.Descending;
}
got An error: Argument NUll Exception Was Unhandled ..
Value cannot be null.
Parameter name: dataGridViewColumn
would any one help on this....
I have tried the following code and it works, I don't have images so I used empty column. The code is bit long because I had to implement BindingList<T> to implement sorting. You can read more about the implementation of BindingList<T> in this answer and here. You can find more about AutoPoco here.
using AutoPoco.Engine;
using AutoPoco;
using AutoPoco.DataSources;
namespace GridViewSorting
{
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
}
private void TestForm_Load(object sender, EventArgs e)
{
LoadGridData();
}
private void gv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
var newcolumn = gv.Columns[e.ColumnIndex];
var showColumn = newcolumn;
ListSortDirection direction;
var sortedColumn = gv.SortedColumn;
var sd = sortedColumn==null? SortOrder.None:sortedColumn.HeaderCell.SortGlyphDirection;
if (sortedColumn == newcolumn && sd == gv.SortOrder)
return;
if (sd == SortOrder.Descending || sd == SortOrder.None)
{
sd = SortOrder.Ascending;
direction = ListSortDirection.Ascending;
}
else
{
sd = SortOrder.Descending;
direction = ListSortDirection.Descending;
}
//now the fun begins, suppose this is image column and you want to
//sort based on product name when product image column header
//is clicked.
if (newcolumn.HeaderText == "ProductImage")//check if image column
{
newcolumn = gv.Columns["ProductName"];//sort on product names
}
gv.Sort(newcolumn, direction);
newcolumn.HeaderCell.SortGlyphDirection = SortOrder.None;
showColumn.HeaderCell.SortGlyphDirection = sd;//change sort indicator on clicked column
}
private void LoadGridData()
{
IGenerationSessionFactory factory = AutoPocoContainer.Configure(x =>
{
x.Conventions(c => { c.UseDefaultConventions(); });
x.AddFromAssemblyContainingType<SimpleProduct>();
x.Include<SimpleProduct>()
.Setup(c => c.ProductName).Use<FirstNameSource>()
.Setup(c => c.Id).Use<IntegerIdSource>()
.Setup(c => c.ProductDescription).Use<RandomStringSource>(5, 20);
});
var session = factory.CreateSession();
var r = new Random(234234);
var rn = r.Next(5, 100);
IList<SimpleProduct> products = session.List<SimpleProduct>(25)
.Impose(x => x.Price, r.Next() * rn)
.Get();
var bl = new ProductList();
foreach (var i in products)
{
bl.Add(i);
}
gv.DataSource = bl;
}
}
public class ProductList : SortableProductList<SimpleProduct>
{
protected override Comparison<SimpleProduct> GetComparer(PropertyDescriptor prop)
{
Comparison<SimpleProduct> comparer;
switch (prop.Name)
{
case "Id":
comparer = new Comparison<SimpleProduct>(delegate(SimpleProduct x, SimpleProduct y)
{
if (x != null)
if (y != null)
return (x.Id.CompareTo(y.Id));
else
return 1;
else if (y != null)
return -1;
else
return 0;
});
break;
case "ProductName":
comparer = new Comparison<SimpleProduct>(delegate(SimpleProduct x, SimpleProduct y)
{
if (x != null)
if (y != null)
return (x.ProductName.CompareTo(y.ProductName));
else
return 1;
else if (y != null)
return -1;
else
return 0;
});
break;
case "ProductDescription":
comparer = new Comparison<SimpleProduct>(delegate(SimpleProduct x, SimpleProduct y)
{
if (x != null)
if (y != null)
return (x.ProductDescription.CompareTo(y.ProductDescription));
else
return 1;
else if (y != null)
return -1;
else
return 0;
});
break;
case "Price":
comparer = new Comparison<SimpleProduct>(delegate(SimpleProduct x, SimpleProduct y)
{
if (x != null)
if (y != null)
return (x.Price.CompareTo(y.Price));
else
return 1;
else if (y != null)
return -1;
else
return 0;
});
break;
default:
comparer = new Comparison<SimpleProduct>((x, y) =>
{
if (x != null && y != null)
return x.GetHashCode().CompareTo(y.GetHashCode());
return 0;
});
break;
}
return comparer;
}
}
public abstract class SortableProductList<T> : BindingList<T>
{
protected override bool SupportsSortingCore{get{return true;}}
protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
if (prop.PropertyType.GetInterface("IComparable") == null)return;
var itemsList = (List<T>)this.Items;
Comparison<T> comparer = GetComparer(prop);
itemsList.Sort(comparer);
if (direction == ListSortDirection.Descending) itemsList.Reverse();
}
protected abstract Comparison<T> GetComparer(PropertyDescriptor prop);
}
public class SimpleProduct
{
public int Id { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public string ProductImage { get; set; }
public string ProductDescription { get; set; }
}
}
You will get your thing in gv_ColumnHeaderMouseClick function.