How to Edit/Update Data in Collection in C# - c#

I have a collection in my C# code
private ObservableCollection<UserForms> _userForms =
new ObservableCollection<UserForms>();
public ObservableCollection<UserForms> UserForms { get { return _userForms; } }
I am filling collection with 4 values
foreach (DataRow dr in DataTable.Rows)
{
UserForms.Add(new UserForms()
{
FormID = Convert.ToInt32(dr["FormID"]),
FormName = dr["FormName"].ToString(),
FromSyName = dr["FormSyName"].ToString(),
Visibility = false,
RoleAdd=false,
RoleEdit=false,
RoleDelete=false
});
}
I am filling this in Form_Load() event
Now I want to update
Visibility = true,
RoleAdd=true,
RoleEdit=true,
RoleDelete=true
in specified row in the collection.

You simply need to do the following:
UserForms[0].Visibility = true;
where "[0]" is the index.

If your ObservableCollection is enumerable (which collections usually are) you can use a foreach loop as follows:
foreach(UserForms uf in UserForms)
{
if (uf.FormID > 10)
uf.Visibility = true;
}
In the above code, I change the visibility of rows which their FormID is higher than 10.

Looks like you need filter out some items and then update them.
foreach(UserForms uf in UserForms.Where(i=>i.FormName == "FormName"/*put your filtering criteria here*/))
{
uf.Visibility = true;
// Set all needed properties here
}

You want to access the instance of collection.
_userForms.ToList().ForEach((f) => f.Visibility = true);
or if you know the index and want to update individual item.
_userForms[index].Visibility = true;
or for multiple filter items
var filterColl = coll.Where((c)=> c.FormName.StartsWith("A"));
filterColl.ToList().ForEach((f) => f.Visibility = true);
hope this helps..

Related

SaveChanges problem in N-Tier Architecture

Normally, with MVC I use db.savechanges() method after I do some processes. But check the below code when I use N-Tier Architecture in everyloop its gonna insert in this way but I dont want it. I have to check all the items first. If there is no problem then I have to insert it all together.
foreach (var item in mOrderList)
{
MOrder mOrder = new MOrder();
mOrder.StatusAdmin = false;
mOrder.Date = DateTime.Now;
mOrder.StatusMVendor = "Sipariş alındı.";
mOrder.HowMany = item.HowMany;
mOrder.MBasketId = item.MBasketId;
mOrder.MProductId = item.MProductId;
mOrder.MVendorId = item.MVendorId;
mOrder.WInvestorId = item.WInvestorId;
MProduct mprostock = _imProductService.GetMProductById(item.MProductId);
if (mprostock.Stock<=0)
{
return ReturnErrorAndSuccess(HttpStatusCode.NotFound, "MProduct", mprostock.Name + " ürününde stok kalmadığı için işlem tamamlanamadı.");
}
_imOrderService.InsertMOrder(mOrder);
}
all you have to do is:
first you should define a method that get list of mProductId and then return list of MProduct.
after that you should check if there is any record with Stock<=0 then return your error.
-also for your insert you should define a method that get list of MOrder and return appropriate datatype for example Boolean.
public List<MProduct> GetMProductByIds(List<MProductId> mProductId)
{
//getting record code
}
public bool AddMOrder(List<MOrder> mOrder)
{
//inserting record code
}

DevExpress XtraGrid force filter to display individual values for RepositoryItemCheckedComboBoxEdit column

I have added a column with RepositoryItemCheckedComboBoxEdit as an editor. Each row for that column can feature one or more entries from a predefined list of categories (let's call them Category1, Category2 and Category3) which are strings and are read from the database.
My problem is that the filter will list options such as: "Category1; Category2" as well as "Category1" or "Category1; Category2; Category3", depending on what it finds in the grid for said column (if one of the rows has all three categories selected that will be considered an individual filter option, instead of breaking down the value into its components).
I would like the filter to only list single values, instead of combinations, but I'm unable to find a solution for that. I have tried using the ShowFilterPopupCheckedListBox event in order to manipulate the filter contents, but now filtering has stopped working for that column altogether.
Here is my code:
void gridView_ShowFilterPopupCheckedListBox(object sender, DevExpress.XtraGrid.Views.Grid.FilterPopupCheckedListBoxEventArgs e)
{
List<CheckedListBoxItem> atomicValues = new List<CheckedListBoxItem>();
if (e.Column.FieldName != "CategoryCollection") { return; }
for (int i = 0; i < e.CheckedComboBox.Items.Count; i++)
{
CheckedListBoxItem item = e.CheckedComboBox.Items[i];
string itemValue = (string)(item.Value as FilterItem).Value;
string[] atomicItemValues = itemValue.Split(';');
foreach (string atomicValue in atomicItemValues)
{
string trimmedAtomicValue = atomicValue.Trim();
atomicValues.Add(new CheckedListBoxItem(trimmedAtomicValue));
}
}
List<CheckedListBoxItem> distinctAtomicValues = atomicValues.GroupBy(x => x.Value).Select(group => group.First()).OrderBy(x => x.Value).ToList();
e.CheckedComboBox.Items.Clear();
foreach (CheckedListBoxItem atomicItem in distinctAtomicValues)
{
e.CheckedComboBox.Items.Add(atomicItem);
}
}
As I know, checked filter dropdown list does not allow to add custom items.
As an alternative solution, you can use the Auto Filter Row for filtering a column by using an in-place CheckedComboBoxEdit:
Enable GridView.OptionsView.ShowAutoFilterRow property to true.
Assign in-place CheckedComboBoxEdit to auto filter row cell
Handle the GridView.CustomRowCellEdit event in the following way:
-
private void gridView_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
{
if (e.Column.FieldName == "YourField" && e.RowHandle == GridControl.AutoFilterRowHandle)
{
e.RepositoryItem = repositoryItemCheckedComboBoxEdit;
}
}
There are no build-in functions in GridView, so you need to create your custom descendant from GridView class.
You need to apply your custom filter criteria, because default GridView are applying equals operator for checked filter, but you need to use contains criteria. For this you need to ovveride ApplyCheckedColumnFilter method of GridView.
Also if you want to show currently applied filters in popup, then you need to update FilterValues property of CheckedColumnFilterPopup.RepositoryItemFilterComboBox object. You can get this object from FilterPopupCheckedListBoxEventArgs.CheckedComboBox property by casting it to CheckedColumnFilterPopup.RepositoryItemFilterComboBox.
Here is example:
Custom GridView descendant:
public class CustomGridView : GridView
{
protected override void ApplyCheckedColumnFilter(GridColumn column, object stringValues, List<object> checkedValues)
{
if (column.ColumnEdit is RepositoryItemCheckedComboBoxEdit)
{
var groupOperator =
new GroupOperator(
GroupOperatorType.Or,
from checkedValue in checkedValues
where checkedValue != null
select
new FunctionOperator(
FunctionOperatorType.Contains,
new OperandProperty(column.FieldName),
new OperandValue(checkedValue)));
ColumnFilterInfo filterInfo;
switch (groupOperator.Operands.Count)
{
case 0:
filterInfo = new ColumnFilterInfo();
break;
case 1:
filterInfo = new ColumnFilterInfo(groupOperator.Operands[0]);
break;
default:
filterInfo = new ColumnFilterInfo(groupOperator);
break;
}
column.FilterInfo = filterInfo;
}
else
base.ApplyCheckedColumnFilter(column, stringValues, checkedValues);
}
}
ShowFilterPopupCheckedListBox event handler method:
private void gridView1_ShowFilterPopupCheckedListBox(object sender, FilterPopupCheckedListBoxEventArgs e)
{
if (!(e.Column.ColumnEdit is RepositoryItemCheckedComboBoxEdit)) { return; }
var distinctAtomicValues =
(from value in
(from atomicItemValues in
from item in e.CheckedComboBox.Items.OfType<CheckedListBoxItem>()
let itemValue = (string)(item.Value as FilterItem).Value
where itemValue != null
select itemValue.Split(';')
from atomicValue in atomicItemValues
let trimmedAtomicValue = atomicValue.Trim()
orderby trimmedAtomicValue
select trimmedAtomicValue).Distinct()
select new CheckedListBoxItem(value)).ToList();
e.CheckedComboBox.Items.Clear();
foreach (var atomicItem in distinctAtomicValues)
e.CheckedComboBox.Items.Add(atomicItem);
string filterString = e.Column.FilterInfo.FilterString;
if (!string.IsNullOrEmpty(filterString))
{
var filterItem = (CheckedColumnFilterPopup.RepositoryItemFilterComboBox)e.CheckedComboBox;
filterItem.FilterValues =
string.Join("\n",
from item in filterItem.Items.OfType<CheckedListBoxItem>()
let itemValue = (string)item.Value
where itemValue != null && filterString.Contains("Contains([" + e.Column.FieldName + "], '" + item.Value + "'")
select itemValue);
}
}

How to add multiple attributes to dropdown list at the time of population

i could solved it just by for loops this way
for loop iterate in datasource and rest of the code as follows
ListItem test = new ListItem { Text = srText, Value = srValue}
test.Attributes.Add("data-imagesrc", "xxx");
test.Attributes.Add("data-description", "xxx");
dropListUserImages.Items.Add(test);
may be there could be error in code because i have composed the above code in notepad. i guess my above code approach will solve my problem but just wondering that can i do the same with LINQ.
here i am giving a sample code which populating dropdown by LINQ but not sure that below code will allow us to add multiple attribute value coming from db?
below sample code taken from http://stackoverflow.com/questions/14710841/making-drop-down-list-in-asp-net-by-foreach-loop
var source = Enumerable.Range(1, 1000)
.Select(i => new { Text= i.ToString(), Value=i.ToString() });
test.DataSource = source;
test.DataTextField = "Text";
test.DataValueField = "Value";
test.DataBind();
looking for guidance to achieve the same with LINQ if possible. thanks
You cannot use the DataSource + DataBind approach if you want to add custom attributes. But why don't you use a simple loop?
var source = db.TableName.Take(1000) // if you only want 1000
.Select(sr => new {
srText = sr.srText,
srValue = sr.srValue,
imagesrc = "xxx", // change
description = "xxx" // change
});
foreach(var x in source)
{
ListItem test = new ListItem { Text = x.srText, Value = x.srValue };
test.Attributes.Add("data-imagesrc", x.imagesrc);
test.Attributes.Add("data-description", x.description);
dropListUserImages.Items.Add(test);
}

Create more than one row in a for-each loop

Working on an old application I see this code:, It is using DataTable, DataRow stuff.
foreach (string networkIdToCreate in networkIdsToCreate)
{
HTExtractSchema.HTProviderMedicalGroupContractRow rHTProviderMedicalGroupContract = tblHTProviderMedicalGroupContract.NewHTProviderMedicalGroupContractRow();
rHTProviderMedicalGroupContract.ItemArray = rHTProviderMedicalGroupContractDefaults.ItemArray;
rHTProviderMedicalGroupContract.NetworkId = networkIdToCreate;
rHTProviderMedicalGroupContract.Business = "470";
tblHTProviderMedicalGroupContract.Rows.Add(rHTProviderMedicalGroupContract);
}
So it creates the new row, puts some values in there and adds it to the DataTable.
Now I want to modify it to create two rows instead of one row, all values the same except for "Business" field, it is one line before the last in the code above.
So I did that like this:
foreach (string networkIdToCreate in networkIdsToCreate)
{
HTExtractSchema.HTProviderMedicalGroupContractRow rHTProviderMedicalGroupContract = tblHTProviderMedicalGroupContract.NewHTProviderMedicalGroupContractRow();
rHTProviderMedicalGroupContract.ItemArray = rHTProviderMedicalGroupContractDefaults.ItemArray;
rHTProviderMedicalGroupContract.NetworkId = networkIdToCreate;
rHTProviderMedicalGroupContract.Business = "470";
tblHTProviderMedicalGroupContract.Rows.Add(rHTProviderMedicalGroupContract);
HTExtractSchema.HTProviderMedicalGroupContractRow rHTProviderMedicalGroupContract2 = tblHTProviderMedicalGroupContract.NewHTProviderMedicalGroupContractRow();
rHTProviderMedicalGroupContract2.ItemArray = rHTProviderMedicalGroupContractDefaults.ItemArray;
rHTProviderMedicalGroupContract2.NetworkId = networkIdToCreate;
rHTProviderMedicalGroupContract2.Business = "475";
tblHTProviderMedicalGroupContract.Rows.Add(rHTProviderMedicalGroupContract2);
}
But I was wondering if there is a better way other than this copy paste? so if someone saw the code won't laugh at me :D
Just add this internal loop
foreach(var business in new[] {"470", "475"})
{
...
rHTProviderMedicalGroupContract.Business = business ;
...
}
EDIT
Or you can use a method
private void CreatRow(
string networkIdToCreate,
string business)
{
HTExtractSchema.HTProviderMedicalGroupContractRow rHTProviderMedicalGroupContract =
tblHTProviderMedicalGroupContract.NewHTProviderMedicalGroupContractRow();
rHTProviderMedicalGroupContract.ItemArray =
rHTProviderMedicalGroupContractDefaults.ItemArray;
rHTProviderMedicalGroupContract.NetworkId = networkIdToCreate;
rHTProviderMedicalGroupContract.Business = business;
tblHTProviderMedicalGroupContract.Rows.Add(rHTProviderMedicalGroupContract);
}
and use it like this
foreach (string networkIdToCreate in networkIdsToCreate)
{
CreatRow(networkIdToCreate, "470");
CreatRow(networkIdToCreate, "475");
if(networkIdToCreate == "2" || networkIdToCreate == "6")
{
CreateRow(networkIdToCreate, "474");
}
}
Note you may need to pass in tblHTProviderMedicalGroupContract depending on its scope,

How to make a checkbox disabled without using any specific condition?

I have a checkbox whose value is handled from the DB on the basis of the column isAllow. We have 5 names and corresponding to these name we have diff isAllow property. If the value of isAllow is true then the checkbox get checked.
For four names, I have to make the checkbox as checked, but for one specific name out of 5, I have to mark the checkbox as disabled as well. I can achieve this by adding a condition as:
if(name=="Josh" && isAllow)
{
chkBrand.Enable=false;
chkBrand.Checked=true;
}
I dont want to use the above condition here. I just want to get the checkbox as disable for a specific name without the condition.
Below is the code that I have used:
bool isAllow = false;
bool SigCard = false;
List<AOTLuAffinity> oAotluAffinity = bsAffinity.DataSource as List<AOTLuAffinity>;
foreach (AOTLuAffinity oAffinity in oAotluAffinity)
{
if (oAffinity.Name == comboName.SelectedValue.ToString())
{
isAllow = oAffinity.isAllowName;
signCard = AOTHelper.GetHasSigCardValue(workflowid, Acct.AffinityNum, comboPaBranch.SelectedValue.ToString(), Applicants.AffinityNum, isSignCard, isAllow );
if (isAllow)
{
chkBrand.Checked=true;// here for a specific name, I want to make the checkbox as disabled, but I dont want to use the condition.
}
else
{
chkBrand.Checked=false;
}
break;
}
}
I am finding a hard time in getting this. Any help will be great.
I think the right approach here is to add a new field to the database, isDisabled, and then in your loop evaluate that field:
...
else
{
chkBrand.Checked=false;
}
if (oAffinity.isDisabled)
{
chkBrand.Enabled = false;
}
break;
You can use LINQ conditions to check specific names on a list. You must declare a list like this:
List<Person> peopleList = new List<Person>();
And here is your condition code:
foreach (AOTLuAffinity oAffinity in oAotluAffinity)
{
if (oAffinity.Name == comboName.SelectedValue.ToString())
{
isAllow = oAffinity.isAllowName;
signCard = AOTHelper.GetHasSigCardValue(workflowid, Acct.AffinityNum, comboPaBranch.SelectedValue.ToString(), Applicants.AffinityNum, isSignCard, isAllow );
chkBrand.Checked =
peopleList
.Count(c => c.Name == comboName.SelectedValue.ToString()) > 0 ? true : false;
break;
}
}
Loop on the items you got from database and each time read value (isAllow),then
chkBrand.Checked=isAllow;

Categories

Resources