动态创建按钮来调用方法,并传递参数 [英] create buttons dynamically to call method and pass in parameter
问题描述
我有一个键值对的字典,需要遍历对,并创造每一个及导线上按钮调用的方法DisplayDocument(字符串ID)的按钮,并通过在Key作为参数。
I have a dictionary with a key value pair and need to loop through the pairs and create a button for each one and wire up the button to call a method DisplayDocument(string Id) and pass in the Key as a parameter.
下面是我有这么远。</ P>
Here's what I have so far.
// test data
var documents= new Dictionary<string,string>();
documents.Add("69110","Diploma");
documents.Add("76404", "Licensure");
foreach (KeyValuePair<string, string> item in documents)
{
MyStringBuilder=MyStringBuilder.Append(item.Value + " " + item.Key + "<br />");
}
printFaxDocuments.InnerHtml = MyStringBuilder.ToString();
我想要做的就是打印出来的文件键和值,然后一个按钮,使用可以点击查看文档。我建立了查看文档的方法,它需要传递的键值。我怎样才能做到这一点?
What i want to do is print out the document Key and Value and then a button that the use can click to view the document. I have the method built to view the document and it requires the Key value to be passed in. How can I do this?
我不知道如何在点缀文本数据的按钮。我需要写出来的键和值添加按钮添加一个&LT; BR /&gt;中
,然后在词典中的下一个项目再次做同样的事情。
I'm not sure how to intersperse the button in the text data. I need to write out the key and value add the button add a "<br/>"
and then do the same thing again for the next item in the dictionary.
推荐答案
下面我在OnInit方法创建的Button控件和他们每个人分配了相同的Click事件处理程序。
Below I have created the Button controls in the OnInit method and assigned each of them the same Click event handler.
密钥存储在其中的事件处理程序检索并传递给DisplayDocument方法按钮CommandArgument属性。
The Key is stored in the Buttons CommandArgument property which is retrieved in the event handler and passed to the DisplayDocument method.
protected override void OnInit(EventArgs e)
{
// test data
var documents = new Dictionary<string, string>();
documents.Add("69110", "Diploma");
documents.Add("76404", "Licensure");
foreach (KeyValuePair<string, string> item in documents)
{
Button button = new Button();
button.Text = string.Format("Button: {0}", item.Key);
button.CommandArgument = item.Key;
button.Click += ButtonClicked;
ButtonContainer.Controls.Add(button);
}
base.OnInit(e);
}
protected void ButtonClicked(object sender, EventArgs e)
{
Button button = (Button) sender;
string id = button.CommandArgument;
DisplayDocument(id);
}
private void DisplayDocument(string id)
{
//Do something
}
修改
您可能最好使用CSS来设置按钮的布局。
You are probably better off using CSS to set the layout for the Buttons.
尝试添加以下CSS类到你的页面(或样式表文件)的头
Try adding the following CSS class to the head of your page (or stylesheet file)
<style type="text/css">
.stacked-button
{
display:block;
}
</style>
然后添加以下按钮创建code:
And then add the following to the button creation code:
button.CssClass = "stacked-button";
您就可以添加到CSS类为需要修改布局(页边距等)
You can then add to the CSS class as required to modify the layout (margins etc.)
希望这有助于。
这篇关于动态创建按钮来调用方法,并传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!