5

I am filling the Excel cells as row and column using C# in my entire project as given below. Now there is a new requirement to add a dropdownlist in the particular cell.

var oXl = new Microsoft.Office.Interop.Excel.Application {DisplayAlerts = false};
var oWb = oXl.Workbooks.Open(excelFileName);
Microsoft.Office.Interop.Excel._Worksheet oSheet = oWb.Sheets[2];
oSheet.Cells[row, 1] = changeName + "\t";
oSheet.Cells[row, 2] = newName + "\t";
oSheet.Cells[row, 3] = (i + 1) + "\t";
oSheet.Cells[row, 4] = filename;
oSheet.Cells[row, 5] = type;
oSheet.Cells[row, 8] = dropdown; // Here I need to add a dropdown list

How can I do this?

1 Answer 1

16

First make a list for dropdown

        var list = new System.Collections.Generic.List<string>();
        list.Add("Charlie");
        list.Add("Delta");
        list.Add("Echo");
        var flatList = string.Join(",", list.ToArray());

then add this list as dropdown in the particular cell as below

var cell = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[row, 8];
            cell.Validation.Delete();
            cell.Validation.Add(
               XlDVType.xlValidateList,
               XlDVAlertStyle.xlValidAlertInformation,
               XlFormatConditionOperator.xlBetween,
               flatList,
               Type.Missing);

            cell.Validation.IgnoreBlank = true;
            cell.Validation.InCellDropdown = true;
Sign up to request clarification or add additional context in comments.

6 Comments

add default value like as cell.Value = "default value";
If you are quoting from another source, at least give credit to the original author: clear-lines.com/blog/post/…
@TotZam - no, not necessary. If you were to credit code reuse as a developer you'd be there all day. This is pretty bog-standard stuff.
I don't know if it used to be like this or if there is a mistake in the writing of the answer. Combining with "," doesn't work. ";" combining is necessary. stackoverflow.com/a/65697065/14875740
@OzgurSaklanmaz Combine with CultureInfo.CurrentCulture.TextInfo.ListSeparator to avoid Locale issues (instead of , or ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.