Add click if statement - c#

Is there a better way to pass this through the addClick (ideally I don't want this at all and I would want it to auto-pass through)?
public void addClick(object sender, EventArgs e)
{
if ((string) HttpContext.Current.Session["whichMenu"] == "systemDateFormats")
{
WorldViewNet.system.DateFormats dateformats = new WorldViewNet.system.DateFormats();
dateformats.addClick();
}
else if ((string) HttpContext.Current.Session["whichMenu"] == "programmingLabels")
{
WorldViewNet.programming.Labels labels = new WorldViewNet.programming.Labels();
labels.addClick();
}
else if ((string) HttpContext.Current.Session["whichMenu"] == "programmingPLUSearch")
{
WorldViewNet.programming.PLUSearch pluSearch = new WorldViewNet.programming.PLUSearch();
pluSearch.addClick();
}
else if ((string) HttpContext.Current.Session["whichMenu"] == "programmingServings")
{
WorldViewNet.programming.Servings servings = new WorldViewNet.programming.Servings();
servings.addClick();
}
else if ((string) HttpContext.Current.Session["whichMenu"] == "programmingShops")
{
WorldViewNet.programming.Shops shops = new WorldViewNet.programming.Shops();
shops.addClick();
}
else if ((string) HttpContext.Current.Session["whichMenu"] == "programmingTextsSearch")
{
WorldViewNet.programming.TextsSearch textsSearch = new WorldViewNet.programming.TextsSearch();
textsSearch.addClick();
}
else if ((string) HttpContext.Current.Session["whichMenu"] == "systemTemplates")
{
WorldViewNet.system.Templates templates = new WorldViewNet.system.Templates();
templates.addClick();
}
}
If anyone has any suggestions, that would help me out I would be grateful.

I thing below models maybe good for your codes:
public void addClick(object sender, EventArgs e)
{
object control;
string opt = (string) HttpContext.Current.Session["whichMenu"];
switch (opt)
{
case "systemDateFormats": control = new WorldViewNet.system.DateFormats();
break;
case "programmingLabels": control = new WorldViewNet.programming.Labels();
break;
case "programmingPLUSearch": control = new WorldViewNet.programming.PLUSearch();
break;
case "programmingServings": control = new WorldViewNet.programming.Servings();
break;
case "programmingShops": control = new WorldViewNet.programming.Shops();
break;
case "programmingTextsSearch": control = new WorldViewNet.programming.TextsSearch();
break;
case "systemTemplates": control = new WorldViewNet.system.Templates();
break;
default: new WorldViewNet.system.DefaultType();
}
((dynamic)control).addClick();
}

Related

Creating Product Listing Group Tree google ads Api returning INTERNAL_ERROR

I am trying to add a listing group tree in google ads api V10 but it is returning internal error. Here is my code:
public GoogleAwApi.AdGroupCriterionReturnValue MutateProductPartitionsForAdGroupGA(GoogleAwApi.AdGroupCriterionOperation[] operations, long clientId)
{
var result = new GoogleAwApi.AdGroupCriterionReturnValue();
AdGroupCriterionServiceClient service = this.AdGroupCriterionServiceGA;
List<AdGroupCriterionOperation> operationsGA = new List<AdGroupCriterionOperation>();
List<GoogleAwApi.AdGroupCriterion> results = new List<GoogleAwApi.AdGroupCriterion>();
List<GoogleAwApi.ApiError> partialFailures = new List<GoogleAwApi.ApiError>();
foreach (var item in operations)
{
try
{
var operand = (GoogleAwApi.BiddableAdGroupCriterion)item.operand;
// Start creating the criteron...
GoogleAdsResources.AdGroupCriterion adGroupCriterion = new GoogleAdsResources.AdGroupCriterion()
{
// The resource name the criterion will be created with. This will define the ID
// for the ad group criterion.
AdGroup = ResourceNames.AdGroup(clientId, item.operand.adGroupId),
//ResourceName = ResourceNames.AdGroupCriterion(clientId, item.operand.adGroupId, item.operand.criterion.id),
Status = Google.Ads.GoogleAds.V10.Enums.AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Enabled
};
switch (operand.userStatus)
{
case GoogleAwApi.UserStatus.ENABLED:
adGroupCriterion.Status = AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Enabled;
break;
case GoogleAwApi.UserStatus.REMOVED:
adGroupCriterion.Status = AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Removed;
break;
case GoogleAwApi.UserStatus.PAUSED:
adGroupCriterion.Status = AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Paused;
break;
default:
adGroupCriterion.Status = AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Enabled;
break;
}
string cType = item.operand.criterion.GetType().Name;
if (operand.biddingStrategyConfiguration != null)
{
var bids = operand.biddingStrategyConfiguration.bids;
var thidBid = (GoogleAwApi.CpcBid)bids[0];
adGroupCriterion.CpcBidMicros = thidBid.bid.microAmount;
adGroupCriterion.EffectiveCpcBidSource = Google.Ads.GoogleAds.V10.Enums.BiddingSourceEnum.Types.BiddingSource.AdGroup;
}
adGroupCriterion.ApprovalStatus = APIHelper.MapApprovalStatus(operand.approvalStatus);
adGroupCriterion.BidModifier = operand.bidModifier;
var criterion = (GoogleAwApi.ProductPartition)item.operand.criterion;
adGroupCriterion.CriterionId = criterion.id;
ListingGroupTypeEnum.Types.ListingGroupType lType = ListingGroupTypeEnum.Types.ListingGroupType.Unknown;
if (criterion.partitionType == GoogleAwApi.ProductPartitionType.SUBDIVISION)
{
lType = ListingGroupTypeEnum.Types.ListingGroupType.Subdivision;
adGroupCriterion.ResourceName = ResourceNames.AdGroupCriterion(clientId, item.operand.adGroupId, item.operand.criterion.id);
}
if (criterion.partitionType == GoogleAwApi.ProductPartitionType.UNIT)
{
lType = ListingGroupTypeEnum.Types.ListingGroupType.Unit;
}
var casevalue = (GoogleAwApi.ProductDimension)criterion.caseValue;
var lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Unknown;
var cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Unknown;
var lValue = "";
Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo listingDimensionInfo = null;
if (casevalue != null)
{
//Get listing Group Info
switch (casevalue.ProductDimensionType)
{
case "ProductType":
if (casevalue != null)
{
string[] caseValueItems = casevalue.ToString().Split(',');
if (caseValueItems.Length == 2)
{
if (caseValueItems[0].Contains("PRODUCT_TYPE_L1"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level1;
if (caseValueItems[0].Contains("PRODUCT_TYPE_L2"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level2;
if (caseValueItems[0].Contains("PRODUCT_TYPE_L3"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level3;
if (caseValueItems[0].Contains("PRODUCT_TYPE_L4"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level4;
if (caseValueItems[0].Contains("PRODUCT_TYPE_L5"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level5;
string[] lValueItems = caseValueItems[1].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
if (String.IsNullOrEmpty(lValue))
{
//isEverythingElse
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductType = new Google.Ads.GoogleAds.V10.Common.ProductTypeInfo
{ Level = lLevel }
};
}
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductType = new Google.Ads.GoogleAds.V10.Common.ProductTypeInfo
{ Level = lLevel, Value = lValue }
};
}
}
break;
case "Brand":
if (casevalue != null)
{
string[] caseValueItems = casevalue.ToString().Split(',');
if (caseValueItems.Length == 2)
{
string[] lValueItems = caseValueItems[1].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
}
if (caseValueItems.Length == 1)
{
string[] lValueItems = caseValueItems[0].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
}
//isEverythingElse
if (String.IsNullOrEmpty(lValue))
{
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductBrand = new Google.Ads.GoogleAds.V10.Common.ProductBrandInfo()
};
}
else
{
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductBrand = new Google.Ads.GoogleAds.V10.Common.ProductBrandInfo
{ Value = lValue }
};
}
}
break;
case "Custom":
if (casevalue != null)
{
string[] caseValueItems = casevalue.ToString().Split(',');
if (caseValueItems.Length == 2)
{
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_0"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index0;
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_1"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index1;
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_2"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index2;
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_3"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index3;
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_4"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index4;
string[] lValueItems = caseValueItems[1].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
if (String.IsNullOrEmpty(lValue))
{
//isEverythingElse
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductCustomAttribute = new Google.Ads.GoogleAds.V10.Common.ProductCustomAttributeInfo
{ Index = cIndex }
};
}
else
{
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductCustomAttribute = new Google.Ads.GoogleAds.V10.Common.ProductCustomAttributeInfo
{ Index = cIndex, Value = lValue }
};
}
}
}
break;
case "OfferId":
if (casevalue != null)
{
string[] caseValueItems = casevalue.ToString().Split(',');
if (caseValueItems.Length == 2)
{
string[] lValueItems = caseValueItems[1].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
}
if (caseValueItems.Length == 1)
{
string[] lValueItems = caseValueItems[0].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
}
if (String.IsNullOrEmpty(lValue))
{
//isEverythingElse
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductItemId = new Google.Ads.GoogleAds.V10.Common.ProductItemIdInfo()
};
}
else
{
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductItemId = new Google.Ads.GoogleAds.V10.Common.ProductItemIdInfo
{ Value = lValue }
};
}
}
break;
default:
break;
}
}
Google.Ads.GoogleAds.V10.Common.ListingGroupInfo ListingGroup = new Google.Ads.GoogleAds.V10.Common.ListingGroupInfo()
{
Type = lType, // SubDivision OR Unit
CaseValue = listingDimensionInfo
};
if (criterion.id != -1)
ListingGroup.ParentAdGroupCriterion = ResourceNames.AdGroupCriterion(clientId, item.operand.adGroupId, criterion.parentCriterionId);
adGroupCriterion.ListingGroup = ListingGroup;
adGroupCriterion.CriterionId = criterion.id;
if (item.#operator == GoogleAwApi.Operator.ADD) { operationsGA.Add(new AdGroupCriterionOperation() { Create = adGroupCriterion }); }
if (item.#operator == GoogleAwApi.Operator.REMOVE) { operationsGA.Add(new AdGroupCriterionOperation() { Remove = adGroupCriterion.ResourceName }); }
if (item.#operator == GoogleAwApi.Operator.SET) { operationsGA.Add(new AdGroupCriterionOperation() { Update = adGroupCriterion }); }
}
catch (Exception ex)
{
string except = ex.Message;
}
}
try
{
// Issues a mutate request to process Ads.
MutateAdGroupCriteriaResponse retVal = service.MutateAdGroupCriteria(
new MutateAdGroupCriteriaRequest()
{
CustomerId = clientId.ToString(),
Operations = { operationsGA },
PartialFailure = true,
ValidateOnly = false,
ResponseContentType = ResponseContentTypeEnum.Types.ResponseContentType.MutableResource // required to bring back a complete mutated object to report on.
});
if (retVal.Results[0].AdGroupCriterion != null)
results.Add(APIHelper.MapAdGroupCriterion(retVal.Results[0].AdGroupCriterion));
if (retVal.PartialFailureError != null)
{
var ApiError = new ApiErrorGA();
ApiError.errorString = retVal.PartialFailureError.Message;
ApiError.ApiErrorType = retVal.PartialFailureError.GetType().ToString();
partialFailures.Add(ApiError);
}
}
catch (GoogleAdsException ex)
{
string except = ex.Message;
}
result.ListReturnValueType = "AdGroupAdService";
result.value = results.ToArray();
result.partialFailureErrors = partialFailures.ToArray();
return result;
}
I need the code to be able to create new trees and also replace existing one.
I have tried a lot of different possibilities of trying to get it to work but all return internal error which really doesn't give me any pointers on what the issue is. Any help will be appreciated.

how to simplify the switch case statement in MVC model?

i've this code to insert in DB the data from the "hours1, hours2, hours3" that cames from an excel import, but this makes the code bigger by the way im doing, this is my code, how can i simplfy the part of the hours1,hours2 == nulls.. ?
switch (colNames.IndexOf(item2))
{
case 0:
if (model.Hours == null)
{
item.Hours = 0;
}
else
{
item.Hours = (decimal)model.Hours;
item.Hours_Remaining = (decimal)model.Hours;
}
break;
case 1:
if (model.Hours1 == null)
{
item.Hours = 0;
}
else
{
item.Hours = (decimal)model.Hours1;
item.Hours_Remaining = (decimal)model.Hours;
}
break;
case 2:
if (model.Hours2 == null)
{
item.Hours = 0;
}
else
{
item.Hours = (decimal)model.Hours2;
item.Hours_Remaining = (decimal)model.Hours;
}
break;
case 3:
if (model.Hours == null)
{
item.Hours = 0;
}
else
{
item.Hours = (decimal)model.Hours3;
item.Hours_Remaining = (decimal)model.Hours;
}
break;
}
you can have a private method like this
private void NameOfPrivateMethod(object objValue,Hours hours,Item item)
{
if (objValue == null)
{
item.Hours = 0;
}
else
{
item.Hours = (decimal)objValue;
item.Hours_Remaining = (decimal)hours;
}
}
and use it like this (you need to make some changes to it according to your need)
NameOfPrivateMethod(model.Hours1, model.Hours,Item)

C# - Effeciently writing code

I am pasting my code snippet below. Could some body suggest a better and effecient way of writing this. I would like minimum code to be written and avoid repetition.
private void SetControlVisibility()
{
if (DropDownList1.SelectedItem.Text.Equals("GetAssetsBasicById") || DropDownList1.SelectedItem.Text.Equals("GetAssetDetailsByIds"))
{
Label2.Text = "(Please enter asset ids for e.g. 1,2)";
chkExcludeMAPFunds.Visible = false;
chkPublishXML.Visible = true;
}
else if (DropDownList1.SelectedItem.Text.Equals("GetAssetsBasicBySedols") || DropDownList1.SelectedItem.Text.Equals("GetAssetDetailsBySedols"))
{
Label2.Text = "(Please enter sedols for e.g. B1YW440,0003496)";
chkExcludeMAPFunds.Visible = false;
chkPublishXML.Visible = true;
}
else if (DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportByIds"))
{
Label2.Text = "(Please enter asset ids for e.g. 1:100)";
chkExcludeMAPFunds.Visible = true;
chkPublishXML.Visible = false;
}
else if (DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportBySedol"))
{
Label2.Text = "(Please enter sedols for e.g. B1YW440:100)";
chkExcludeMAPFunds.Visible = true;
chkPublishXML.Visible = false;
}
}
You could use a dictionary to avoid both nested if's and switch/cases:
private readonly Dictionary<string, Tuple<string, bool, bool>> _dropDownMap = new Dictionary<string, Tuple<string, bool, bool>>
{
{"GetAssetsBasicById", new Tuple<string, bool, bool>("(Please enter asset ids for e.g. 1,2)", false, true) },
{"GetAssetDetailsByIds", new Tuple<string, bool, bool>("(Please enter asset ids for e.g. 1,2)", false, true) },
...
};
private void SetControlVisibility()
{
var mapping = _dropDownMap[DropDownList1.SelectedItem.Text];
if (mapping != null)
{
Label2.Text = mapping.Item1;
chkExcludeMAPFunds.Visible = mapping.Item2;
chkPublishXML.Visible = mapping.Item3;
}
}
If you favour readability over small code, then the Tuple could be replaced by an explicit VO class:
private class DropDownMappings
{
public DropDownMappings(label, excludeMAPFundsVisible, publishXMLVisible)
{
Label2Text = label;
ExcludeMAPFundsVisible = excludeMAPFundsVisible;
PublishXMLVisible = publishXMLVisible;
}
public string Label2Text { get; set; }
public bool ExcludeMAPFundsVisible { get; set; }
public bool PublishXMLVisible { get; set; }
}
private readonly Dictionary<string, DropDownMappings> _dropDownMap = new Dictionary<string, DropDownMappings>
{
{"GetAssetsBasicById", new DropDownMappings("(Please enter asset ids for e.g. 1,2)", false, true) },
{"GetAssetDetailsByIds", new DropDownMappings("(Please enter asset ids for e.g. 1,2)", false, true) },
...
};
private void SetControlVisibility()
{
var mapping = _dropDownMap[DropDownList1.SelectedItem.Text];
if (mapping != null)
{
Label2.Text = mapping.Label2Text;
chkExcludeMAPFunds.Visible = mapping.ExcludeMAPFundsVisible;
chkPublishXML.Visible = mapping.PublishXMLVisible;
}
}
Alternate code with switch:
private void SetControlVisibility()
{
if (DropDownList1.SelectedItem != null)
{
switch (DropDownList1.SelectedItem.Text)
{
case "GetAssetsBasicById":
case "GetAssetDetailsByIds":
Label2.Text = "(Please enter asset ids for e.g. 1,2)";
chkExcludeMAPFunds.Visible = false;
chkPublishXML.Visible = true;
break;
case "GetAssetsBasicBySedols":
case "GetAssetDetailsBySedols":
Label2.Text = "(Please enter sedols for e.g. B1YW440,0003496)";
chkExcludeMAPFunds.Visible = false;
chkPublishXML.Visible = true;
break;
case "GetInvestmentReportByIds":
Label2.Text = "(Please enter asset ids for e.g. 1:100)";
chkExcludeMAPFunds.Visible = true;
chkPublishXML.Visible = false;
break;
case "GetInvestmentReportBySedol":
Label2.Text = "(Please enter sedols for e.g. B1YW440:100)";
chkExcludeMAPFunds.Visible = true;
chkPublishXML.Visible = false;
break;
default:
// we do it wrong :(
throw new NotSupportedException();
}
}
}
Another solution is using Item's Tag property with predefined enum values.
My alternate code:
private void SetControlVisibility()
{
string resultText;
bool b = false;
switch (DropDownList1.SelectedItem.Text)
{
case "GetAssetsBasicById":
case "GetAssetDetailsByIds":
b = true;
resultText = "(Please enter asset ids for e.g. 1,2)";
break;
case "GetAssetsBasicBySedols":
case "GetAssetDetailsBySedols":
b = true;
resultText = "(Please enter sedols for e.g. B1YW440,0003496)";
break;
case "GetInvestmentReportByIds":
resultText = "(Please enter asset ids for e.g. 1:100)";
break;
case "GetInvestmentReportBySedol":
resultText = "(Please enter sedols for e.g. B1YW440:100)";
break;
default: return;
}
chkExcludeMAPFunds.Visible = !b;
chkPublishXML.Visible = b;
Label2.Text = resultText;
}
First, taking the chks out of the if and using the ?: operator will shorthand their notation.
Then, due to having only one statement inside each if - else if, brackets can be erased.
if (DropDownList1.SelectedItem.Text.Equals("GetAssetsBasicById") || DropDownList1.SelectedItem.Text.Equals("GetAssetDetailsByIds"))
Label2.Text = "(Please enter asset ids for e.g. 1,2)";
else if (DropDownList1.SelectedItem.Text.Equals("GetAssetsBasicBySedols") || DropDownList1.SelectedItem.Text.Equals("GetAssetDetailsBySedols"))
Label2.Text = "(Please enter sedols for e.g. B1YW440,0003496)";
else if (DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportByIds"))
Label2.Text = "(Please enter asset ids for e.g. 1:100)";
else if (DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportBySedol"))
Label2.Text = "(Please enter sedols for e.g. B1YW440:100)";
chkExcludeMAPFunds.Visible = (DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportByIds") || DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportBySedol") ? true : false;
chkPublishXML.Visible = (DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportByIds") || DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportBySedol") ? false : true;
This way, we have got rid of many lines.

Foreach selected item in Listbox?

I have a dialog that is used to select which forms to show. Originally it was just being selected from a combo box, but now we need to select multiple, so we changed it to a list box.
Here is the method that we used for the combo box:
if (view.ShowDialog() == DialogResult.OK)
{
if (view.FormType == "Form1")
return new Form1_Controller();
else if (view.FormType == "Form2")
return new Form2_Controller();
else if (view.FormType == "Form3")
return new Form3_Controller();
else return null;
}
else
{
return null;
}
How can we encapsulate this in a loop that will return a controller for each selection?
For example, I have tried something like
foreach (ListBoxItem listItem in view.ListBox1)
{
//do if (view.FormType == "Form1")
}
But I don't know the right syntax to use.
To open all forms simultaneously, I would try a different approach something like this
ArrayList controllersSelected = new ArrayList();
foreach (var item in view.ListBox1.SelectedItems)
GetSelectedItem(item.Value, out controllersSelected);
//Your logic to display selected forms simultaneously
DisplaySimultaneousForms(controllersSelected);
private void GetSelectedItem(formName, out ArrayList list)
{
if (view.FormType == "Form1")
list.Add(new Form1_Controller());
else if (view.FormType == "Form2")
list.Add(new Form2_Controller());
else if (view.FormType == "Form3")
list.Add(new Form3_Controller());
}
use SelectedItems:
foreach (var item view.ListBox1.SelectedItems)
SelectForm(item.ToString());
void SelectForm(string value)
{
if(value == "Form1")
return new Form1_Controller();
...
}
You can use below code :
foreach (var item in view.ListBox1.SelectedItems)
{
ShowForm(item.Value);
}
private void ShowForm(formName)
{
if (view.FormType == "Form1")
return new Form1_Controller();
else if (view.FormType == "Form2")
return new Form2_Controller();
else if (view.FormType == "Form3")
return new Form3_Controller();
else return null;
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= listBox1.SelectedItems.Count - 1; i++)
{
switch (listBox1 .Items [i].ToString ())
{
case "FirstForm":
Form2 frm2 = new Form2();
frm2.Show();
break;
case "SecondForm":
Form3 frm3 = new Form3();
frm3.Show();
break;
default:
break;
}
}
}

How to Fire an event for another Control while performing DataGridView_CellContentClick?

Actually, I have fired an event on DataGridView_CellContentClick which perform an operation relating to datagridview like changing cell's value But before performing this action i want to make changes(or fire) an another operation on another control i.e. ListView .But this is not gone happens although i place another operation before datagridview's operation. Anybody please help me out.
And my code goes like this:-
private void dGridDeviceList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//DataGridViewCell dcell = dGridDeviceList.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (e.RowIndex >= 0)
{
ListViewItem litem1 = lvInformation.Items.Add("101");
litem1.SubItems.Add(string.Empty);
litem1.SubItems[1].Text = "Connected.";
ListViewItem litem5= lvErrorList.Items.Add("check ");
Cursor = Cursors.WaitCursor;
List<cException> cxp = new List<cException>();
cDeviceModel cdm = new cDeviceModel();
ListViewItem litem = new ListViewItem();
DataGridViewRow drow = new DataGridViewRow();
cDeviceUtility cUtil = new cDeviceUtility();
List<cAction> catn = new List<cAction>();
drow = dGridDeviceList.Rows[e.RowIndex];
cdm = (cDeviceModel)drow.Tag;
if (e.ColumnIndex == 6)
{
if (dGridDeviceList.CurrentCell.Value.ToString() == "Connect")
{
litem1= lvInformation.Items.Add("101");
litem1.SubItems.Add(string.Empty);
litem1.SubItems[1].Text = "Connected.";
//lvInformation.Items.Insert(0, "101");
//lvInformation.Items[0].SubItems.Add("Connected");
}
// connect disconnect button column
if (cdm.IsConnected)
{
ListViewItem litem2 = lvInformation.Items.Add("102");
litem2.SubItems.Add(string.Empty);
litem2.SubItems[1].Text =string.Format("Disconnecting from {0} device.",dGridDeviceList.CurrentRow.Cells["colDeviceName"].Value);
// then disconnect the device
cdm.IsConnected = false;
cdm.DeviceInterface.Disconnect();
dGridDeviceList.Rows[e.RowIndex].Tag = cdm;
dGridDeviceList.Rows[e.RowIndex].Cells[6].Value = "Connect";
dGridDeviceList.Rows[e.RowIndex].Cells[1].Value = img16x16.Images["notconnected"];
dGridDeviceList.Rows[e.RowIndex].Cells[8].Value= 0;
dGridDeviceList.Rows[e.RowIndex].Cells[8].Tag = "Not Connected";
dGridDeviceList.Refresh();
litem2 = lvInformation.Items.Add("103");
litem2.SubItems.Add(string.Empty);
litem2.SubItems[1].Text = string.Format("Disconnected from {0} device.", dGridDeviceList.CurrentRow.Cells["colDeviceName"].Value);
}
else
{
// string test = lvInformation.Items[0].SubItems[1].ToString();
// catn.Add(new cAction { Number = lvInformation.Items.Count+1, Message = string.Format("Trying to connect with {0}", dGridDeviceList.Rows[e.RowIndex].Cells["colDeviceName"].Value) });
//// lvInformation.Items.Clear();
// foreach (cAction Actn in catn)
// {
// litem=lvInformation.Items.Insert(0, (lvInformation.Items.Count + 1).ToString());
// litem.SubItems.Add(catn[catn.Count -1].Message);
// }
// then connect the device
if (!ConnectToDevice(ref drow, out cxp) == true)
{
foreach (cException err in cxp)
{
litem = lvErrorList.Items.Insert(0, err.Number.ToString());
if (err.EType == ErrorType.Error)
{
litem.ImageKey = "error";
}
else if (err.EType == ErrorType.Warning)
{
litem.ImageKey = "warning";
}
else if (err.EType == ErrorType.Information)
{
litem.ImageKey = "information";
}
litem.SubItems.Add(err.Message);
litem.SubItems.Add(err.Source);
}
}
else
{
dGridDeviceList.Rows[e.RowIndex].Cells[0].Value = true;
dGridDeviceList.Rows[e.RowIndex].Tag = drow.Tag;
dGridDeviceList.Rows[e.RowIndex].Cells[6].Value = "Disconnect";
dGridDeviceList.Rows[e.RowIndex].Cells[1].Value = img16x16.Images["connected"];
dGridDeviceList.Rows[e.RowIndex].Cells[8].Value = 0;
dGridDeviceList.Rows[e.RowIndex].Cells[8].Tag = "Ready";
dGridDeviceList.Refresh();
RemoveSelectionRow();
}
}
}
else if (e.ColumnIndex == 7)
{
// view logs button column
pbarMain.Value = 100;
ViewLogs(dGridDeviceList.Rows[e.RowIndex],ref lvAttnLog ,ref lvErrorList);
}
Cursor = Cursors.Arrow;
}
}
considering this is winform
private void buttonCopyContent_Click(object sender, EventArgs e)
{
//do something
}
you can call this event via following line
this.Invoke(new EventHandler(buttonCopyContent_Click));

Categories