Hide empty columns in DataGridView - c#

I'm working in c# with Windows form.
I've an item DataGridView named objGridView, used like this :
public partial class dlgDetailsObj : Form
{
public dlgDetailsObj(myInterface item)
{
InitializeComponent();
objGridView.DataSource = new BindingList<dlgItem>();
var t = new Task(() =>
{
List<dlgItem> listElements = new List<dlgItem>();
if (item is List<Person>)
{
List<Person> list = (List<Person>)item;
foreach (Person person in list)
{
listElements.Add(new dlgItem()
{
Name = person.Name,
Forname = person.Forname
});
}
}
else if (item is List<Compagny>)
{
List<Compagny> list = (List<Compagny>)item;
foreach (Compagny compagny in list)
{
listElements.Add(new dlgItem()
{
Compagny = compagny.Name
});
}
}
else
{
return;
}
foreach (dlgItem item in listElements)
{
objGridView.Invoke((MethodInvoker)delegate
{
int sel = objGridView.GetSelectedRowIndex();
((BindingList<dlgItem>)objGridView.DataSource).Add(item);
objGridView.SetSelectedRowIndex(sel);
});
}
});
t.Start();
}
}
internal class dlgItem
{
public string Name { get; set; }
public String Forname { get; set; }
public String Compagny { get; set; }
}
The class dlgDetailsObj is used to display a list of Persons/Companies and probably more object later.
My DataGridView has a DataSource filled of dlgItem. Actually all three fields are displayed, even if I only only one.
How can I define my code to display columns only if binded fields are not null ?

If you want to hide all empty columns you could iterate through the DataSource collection to determine whether the corresponding property has been set for any dlgItem object:
public dlgDetailsObj(myInterface item)
{
InitializeComponent();
objGridView.DataSource = new BindingList<dlgItem>();
var t = new Task(() =>
{
...
});
t.Start();
t.ContinueWith(task =>
{
bool displayNameColumn = false;
bool displayFornameColumn = false;
bool displayCompanyColumn = false;
foreach (dlgItem item in (BindingList<dlgItem>)objGridView.DataSource)
{
if (!string.IsNullOrEmpty(item.Name))
displayNameColumn = true;
if (!string.IsNullOrEmpty(item.Forname))
displayFornameColumn = true;
if (!string.IsNullOrEmpty(item.Compagny))
displayCompanyColumn = true;
}
objGridView.Columns[0].Visible = displayNameColumn;
objGridView.Columns[1].Visible = displayFornameColumn;
objGridView.Columns[2].Visible = displayCompanyColumn;
}, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
}

Related

Display data of a class that is in another class datagridview c#

I have a class that contains data from another class:
class SecondClass
{
public FirstClass element { get; set; }
public string note { get; set; }
}
Then I create a list of class elements and display it in the datagridview.
firstarray.Add(new FirstClass() { id = 1, name = "name", password = "text" });
foreach (var item in firstarray)
{
if (item.id == 1)
{
secondarray.Add(new SecondClass() { element = item, note = "text" });
}
}
foreach (var item in secondarray)
{
Console.WriteLine(item.element.id);
}
dataGridView1.DataSource = secondarray;
And I get the wrong output of the items. How do I fix this?

How to check the first item that was checked in a checkbox in asp.net mvc C#

I wanted to know what is the first item that was checked on a checkbox,
Here is my code to know what are the selected item, but I do not know how to know the first item that was checked.
private List<VehicleOptionalEquipment> SelectedEngineOptions(long vehicleId, int? styleId, List<VehicleOptionalEquipment> optionalEquips)
{
var optionEngine = new List<VehicleOptionalEquipment>();
foreach (var optionalEquip in optionalEquips)
{
if (optionalEquip.TypeId == (int)OptionSectionEnum.ENGINE)
{
if (optionalEquip.IsSelected == true)
{
var engineSelected = new VehicleOptionalEquipment
{
TypeId = optionalEquip.TypeId,
Index = optionalEquip.Index,
IsSelected = optionalEquip.IsSelected
};
optionEngine.Add(engineSelected);
}
else
{
var engineNotSelected = new VehicleOptionalEquipment
{
TypeId = optionalEquip.TypeId,
Index = optionalEquip.Index,
IsSelected = optionalEquip.IsSelected
};
optionEngine.Remove(engineNotSelected);
}
}
}
return optionEngine;
}
}
Here is my model:
public class VehicleOptionalEquipment
{
public int TypeId { get; set; }
public int Index { get; set; }
public bool IsSelected { get; set; }
}
Instead of foreach loop and if conditions, you can achieve it in LINQ
var optionEngine = optionalEquips.Where(x => x.TypeId == (int)OptionSectionEnum.ENGINE &&
x.IsSelected).ToList();
You can get the engine type and IsSelected true records to the optionEngine.

Nested List — Get list item of parent list

i want to write a C# function which returns "alamaba" when i pass "Montgomery".
2nd example: Sitka --> Alaska
here is the list of the example:
List<PopulationUSA> result = new List<PopulationUSA>();
PopulationUSA usa = new PopulationUSA("Population in USA", 316128839, new List<PopulationUSA>());
result.Add(usa);
PopulationUSA alabama = new PopulationUSA("Alabama", 4833722, new List<PopulationUSA>());
usa.Items.Add(alabama);
alabama.Items.Add(new PopulationUSA("Birmingham", 212113, null));
alabama.Items.Add(new PopulationUSA("Montgomery", 201332, null));
alabama.Items.Add(new PopulationUSA("Mobile", 194899, null));
PopulationUSA alaska = new PopulationUSA("Alaska", 735132, new List<PopulationUSA>());
usa.Items.Add(alaska);
alaska.Items.Add(new PopulationUSA("Juneau", 32660, null));
alaska.Items.Add(new PopulationUSA("Ketchikan", 8214, null));
alaska.Items.Add(new PopulationUSA("Sitka", 9020, null));
here is the class:
public class PopulationUSA
{
public PopulationUSA(string name, int value, List<PopulationUSA> items)
{
Name = name;
Value = value;
Items = items;
}
public string Name { get; set; }
public int Value { get; set; }
public List<PopulationUSA> Items { get; set; }
}
How can i do that?
Thanks
you can add this method to the PopulationUSA class
public string FindParentsOfGrandChildren(string _name)
{
List<PopulationUSA> parents = Items.Where(s => s.Items.Any(c => c.Name == _name)).ToList();
if (parents != null)
{
string listparents = string.Empty;
for (int i = 0; i < parents.Count; i++)
{
if (i == 0)
{
listparents += parents[i].Name;
}
else
{
listparents += ", " + parents[i].Name;
}
}
return listparents;
}
else
{
return "Not found";
}
}
then use it like this in your example:
string WhereDoIBelong = usa.FindParentsOfGrandChildren("Montgomery")
it would be much better as a recursive method, finding parents of any type (not just "grandchildren") but that is your work!

Find a circular dependency in a collection c#

I've a collection of DataItem class.
DataItem : Property RefItem stores ref to a DataItem that could be same collection.
public class DataItem
{
public int ID { get; set; }
public string Name { get; set; }
public DataItem RefItem { get; set; }
}
Collection:
private List<DataItem> dataitems;
public List<DataItem> DataItems
{
get { return dataitems; }
set { dataitems = value; }
}
Now I have two methods for adding data in the collection and validating data in collection.
public void AddItem(DataItem item)
{
DataItems.Add(item);
}
public bool ValidateDataItems()
{
//Logic for circular reference
//
return true;
}
I want a algorithm in validate method to check if there is any circular dependency in my collection.For ex. Below is an invalid data for me. As item3 is again pointed by item1.
var item1 = new DataItem() {ID=1,Name="First Item",RefItem =null};
var item2 = new DataItem() { ID = 1, Name = "First Item", RefItem = item1 };
var item3 = new DataItem() { ID = 1, Name = "First Item", RefItem = item2 };
item1.RefItem = item3;
AddItem(item1);
AddItem(item2);
AddItem(item3);
If items are added to collection like Item1->item2,item2-> item3,item3->item1 or any other possible combination of where a ref item of a class is pointing back. I want validation method to return false.
It's a circular dependency problem but I couldn't find any concrete algorithm to do so in c#.
Try something like this solution:
public class DataItem
{
public int ID { get; set; }
public string Name { get; set; }
public DataItem RefItem { get; set; }
}
public class Checker
{
public static bool Check(DataItem item)
{
var chain = new Dictionary<DataItem, DataItem>();
chain.Add(item, null);
try
{
ProcessNodes(chain, item);
return true;
}
catch (ArgumentException)
{
return false;
}
}
private static void ProcessNodes(Dictionary<DataItem, DataItem> chain, DataItem item)
{
if (item.RefItem != null)
{
chain.Add(item.RefItem, null);
ProcessNodes(chain, item.RefItem);
}
}
public static bool ValidateDataItems(List<DataItem> items)
{
foreach(var item in items)
if(!Check(item))
return false;
return true;
}
}
public static void Main()
{
var item1 = new DataItem() { ID = 1, Name = "First Item", RefItem = null };
var item2 = new DataItem() { ID = 1, Name = "First Item", RefItem = item1 };
var item3 = new DataItem() { ID = 1, Name = "First Item", RefItem = item2 };
item1.RefItem = item3;
Console.WriteLine(Checker.Check(item1));
item1.RefItem = null;
Console.WriteLine(Checker.Check(item1));
//Sample how to check all existing items
Console.WriteLine(Checker.ValidateDataItems(new List<DataItem>{item1, item2, item3}) ? "items is OK" : "One or more items have dependency");
}

C# - How to search into the ObservableCollection?

I am developing a app in windows phone 7. I have a list box with items of observable collection. Now i want to search into that list box items. I want filter the items which is typed in the Text Box. If i type 'a' mean the list box items should shows the items which is start with 'a'. If i type 'az' mean it should show the items start with 'az'.
public class SortingExampleViewModel : ReactiveObject
{
public string _SearchText = "";
public string SearchText
{
get { return _SearchText; }
set { this.RaiseAndSetIfChanged(x => x.SearchText, value); }
}
public static ObservableCollection<items> _sordtedList;
public ObservableCollection<items> sordtedList
{
get { return _sordtedList; }
set { this.RaiseAndSetIfChanged(x => x.sordtedList, value); }
}
public static ObservableCollection<items> _tempSordtedList;
public ObservableCollection<items> tempSordtedList
{
get { return _tempSordtedList; }
set { this.RaiseAndSetIfChanged(x => x.tempSordtedList, value); }
}
public ReactiveAsyncCommand ExecuteSearch { get; set; }
public SortingExampleViewModel()
{
ObservableCollection<items> myData = new ObservableCollection<items>()
{
new items(){firstName = "Vijay Dhas",age=27},
new items(){firstName = "Ramaraj",age=28},
new items(){firstName = "Arun",age=29},
new items(){firstName = "Prabhu",age=30},
new items(){firstName = "Pranesh",age=31},
new items(){firstName = "Testing",age=32}
};
sordtedList = new ObservableCollection<items>(from i in myData orderby i.firstName select i);
var canConfirm = this.WhenAny(x => x.SearchText, (search) => SearchMethod(search.Value));
ExecuteSearch = new ReactiveAsyncCommand(canConfirm, 0);
}
public Boolean SearchMethod(String searchValue)
{
var col = (ObservableCollection<items>)(sordtedList.Where(p => p.firstName.Contains(searchValue)));
foreach (items objTest in col)
{
tempSordtedList.Add(objTest);
}
sordtedList = tempSordtedList;
return true;
}
}
public class items
{
public string firstName { get; set; }
public int age { get; set; }
}
But here i am getting Error in this line:
var col = (ObservableCollection<items>)(sordtedList.Where(p => p.firstName.Contains(searchValue)));
It showing Unknown error.
Please help me to search in the listbox.
I got the solution.
public SortingExampleViewModel()
{
ObservableCollection<items> myData = new ObservableCollection<items>()
{
new items(){firstName = "Vijay Dhas",age=27},
new items(){firstName = "Ramaraj",age=28},
new items(){firstName = "Arun",age=29},
new items(){firstName = "Prabhu",age=30},
new items(){firstName = "Pranesh",age=31},
new items(){firstName = "Testing",age=32}
};
sordtedList = new ObservableCollection<items>(from i in myData orderby i.firstName select i);
temp = sordtedList;
var canConfirm = this.WhenAny(x => x.SearchText, (search) => SearchMethod(search.Value));
ExecuteSearch = new ReactiveAsyncCommand(canConfirm, 0);
}
public Boolean SearchMethod(String searchValue)
{
ObservableCollection<items> tempList = new ObservableCollection<items>();
tempList = temp;
tempSordtedList = new ObservableCollection<items>();
foreach (items items in tempList)
{
if (items.firstName.ToLower().StartsWith(searchValue.ToLower()))
{
tempSordtedList.Add(items);
}
}
sordtedList = tempSordtedList;
return true;
}
You are casting an IEnumerable (result of the Linq query) to an ObservableCollection.
Use this instead:
var col = sordtedList.Where(p => p.firstName.Contains(searchValue));
Since you only use the variable col to iterate over it, you do not need to cast it.

Categories

Resources