简体   繁体   中英

Passing multiple selected value from a Listbox to an Array as parameters in C#

Below is my C# code to populate the multi-selected items from the listbox

List<string> listCountry = new List<string>();
for (int i = 0; i < lstCountry.Items.Count; i++)
{
   if (lstCountry.Items[i]Selected)
   {
       countries = listCountry.Add(lstCountry.Items[i].ToString());
    }
}     

And I have a line to call the method to run the report with the above parameters:

retVal = CR.GetReport(Company, countries);

My question is : What data type should I define for since it keeps giving me error like "can't implicitly convert type 'void' to 'string'" when I define countries as string countries = null; 定义哪种数据类型,因为当我将国家/地区定义为字符串= null时,它会不断给我一些错误,例如“无法隐式地将类型'void'转换为'string'”; What did I do wrong here? Please help, thank you very much

Sorry I didn't make it clear enough, I have another the function GetReport() which is defined as

public CrystalDecisions.CrystalReports.Engine.ReportDocument GetReport( string      Company,  string countries)
{
    CrystalDecisions.CrystalReports.Engine.ReportDocument retVal = new rptReortData();
     ReportLogon rptLog = new ReportLogon();
     rptLog.logon(retVal, "Report");
     retVal.SetParameterValue("P_Country", new string[] { country});
}  

How do I get the value from the listbox assign to

You didn't provide the name of your function but I guess it's GetReport. It doesn't return any value so you can't assign the retVal. Try the below:

CR.GetReport(Company, countries);

I'm a little puzzled by your question, but I'm guessing that the CR.GetReport function is raising an exception? So your data-type for countries depends on that function.

I might make the following change:

listCountry.Add((lstCountry.Items[i] == null ? string.Empty : lstCountry.Items[i].ToString()));

You need to return retVal from your function

public CrystalDecisions.CrystalReports.Engine.ReportDocument GetReport( string      Company,  string countries)
{
    CrystalDecisions.CrystalReports.Engine.ReportDocument retVal = new rptResearchDataDownload();
     ReportLogon rptLog = new ReportLogon();
     rptLog.logon(retVal, "Report");
     retVal.SetParameterValue("P_Country", new string[] { country});

    // ADD THIS LINE
    return retVal;

}  

Also you need convert the list to a string. You can do this like this:

countries = listCountry.Aggregate((list, c) => list + c + ",");
List<string> listText = new List<string>();
List<string> listValue = new List<string>();
foreach (int index in ListBox1.GetSelectedIndices()) {
    listText.Add(ListBox1.Items[index].Text);
    listValue.Add(ListBox1.Items[index].Value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM