Donald Jansen
Donald Jansen

Reputation: 1985

C# Excel Dropdown on each new Line

Ok I am creating a project that needs to act Similar to the Tasks in TFS when you export the Tasks to Excel and Publish it again. First I am trying to Generate an Excel file with the necessary data, it should populate a dropdown box with Names eg "Donald", "Wilco", "Jansen" etc, with the following code I can add them to a dropdown and add the dropdown to a specific Cell. But I want it to make that collumn to have the dropdowns i.e if I go to cell A1 it should have a dropdown, if I go to cell A2 it should have a dropdown A(x) should always have a drowpdown so If I add information and go to a new Line it should have the dropdown.

Currently I have the following code to start of with, but Have no Idea where to go from here

        var oMissing = Type.Missing;

        var excel = new Application();
        var wb = excel.Workbooks.Add(1);
        var sh = wb.Sheets.Add();
        sh.Name = "TestSheet";
        sh.Cells[1, "A"].Value2 = "SNO";
        sh.Cells[2, "B"].Value2 = "A";
        sh.Cells[2, "C"].Value2 = "1122";

        var range = sh.Range["A1","A1"];
        var xlDropDowns = ((DropDowns)(sh.DropDowns(oMissing)));
        var xlDropDown = xlDropDowns.Add((double)range.Left, (double)range.Top, (double)range.Width, (double)range.Height, false);
        var items = new[] { "Name1", "Name2", "Name3" };

        //Add items into drop down list
        for (int i = 0; i < items.Length; i++)
        {
            xlDropDown.AddItem(items[i], i + 1);
        }

        //wb.Close(true);
        //excel.Quit();
        excel.Visible = true;

Upvotes: 0

Views: 1217

Answers (1)

Donald Jansen
Donald Jansen

Reputation: 1985

Solved it with the following

        var oMissing = Type.Missing;

        var excel = new Application();
        var wb = excel.Workbooks.Add(1);
        var sheet = wb.Sheets.Add();
        sheet.Name = "ClientEditSheet";
        sheet.Visible = false;


        sheet.Range["A1"].Value = "Name1";
        sheet.Range["A2"].Value = "Name2";
        sheet.Range["A3"].Value = "Name3";
        sheet.Range["A4"].Value = "Name4";

        var sheet2 = wb.Sheets["Sheet1"];

        Range validatingCellsRange = sheet2.Range["B1"].EntireColumn;

        var lookupValues = "=ClientEditSheet!$" + "A" + "$1:$" + "A" + "$14";

        validatingCellsRange.Validation.Delete();
        validatingCellsRange.Validation.Add(XlDVType.xlValidateList,
               XlDVAlertStyle.xlValidAlertInformation,
               XlFormatConditionOperator.xlBetween, lookupValues, Type.Missing);
        validatingCellsRange.Validation.IgnoreBlank = true;
        validatingCellsRange.Validation.InCellDropdown = true;

        //wb.Close(true);
        //excel.Quit();
        excel.Visible = true;

Upvotes: 1

Related Questions