如何使用c#在excel的下拉列表中读取所选值 [英] How to read the selected value in dropdown list in excel using c#

查看:119
本文介绍了如何使用c#在excel的下拉列表中读取所选值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



开发一个项目,需要从下拉列表中读取所选值,并为excel中的其他列生成值。有人可以帮忙吗?

以下是代码片段



Hi All,

Im developing a project which requires to read the selected value from the drop down list and generate the values for other columns in the excel. Could Someone please help?
Below is a snippet from the code

var list = new System.Collections.Generic.List<string>();
list.Add("A");
list.Add("B");
list.Add("c");
var flatList = string.Join(",", list.ToArray());


var cell = ws.get_Range("D1", Type.Missing);
 cell.Validation.Delete();
cell.Validation.Add(
   XlDVType.xlValidateList,
   XlDVAlertStyle.xlValidAlertInformation,
   XlFormatConditionOperator.xlBetween,
   flatList,
   Type.Missing);

cell.Validation.IgnoreBlank = true;
cell.Validation.InCellDropdown = true;
cell.Value = "Overall";



我使用上面的代码并成功创建了一个下拉列表。但我不知道如何阅读所选择的值。

我需要一个像这样的代码




I used the above code and was successfully able to create a dropdown list. But i am not sure how to read the valuee that is selected.
I need a code somewhat like this

if(selected option is "A")
{
    Cell D3 value should be ="111";
}
else if (selected option is "B")
{
    cell D3 value should be ="222";
}
else
{
    cell D3 value should be ="333";
}





我们非常感谢任何帮助。 TIA。



Any help would be much appreciated. TIA.

推荐答案

你必须阅读 cell.Value ...



You have to read cell.Value...

var dstCell = ws.get_Range("D3", Type.Missing)
dstCell.Value = cell.Value == "A" ? 111 : (cell=="B" ? 222 : 333);







关于这个答案的评论...

你必须赶上 Worksheet.Change事件 [ ^ ]能够获得更改的值 D1 单元格。



怎么样?请参阅:

如何:在Office项目中创建事件处理程序 [ ^ ]

演练:针对NamedRange控件事件进行编程 [ ^ ]




As to the comment to this answer...
You have to catch Worksheet.Change event[^] to be able to get changed value of D1 cell.

How? Please, see:
How to: Create Event Handlers in Office Projects[^]
Walkthrough: Programming Against Events of a NamedRange Control[^]


这篇关于如何使用c#在excel的下拉列表中读取所选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆