フォームの送信内容に基づいて動的にボタンを作成する C# Web ページを作成しようとしていますが、行き止まりまで実行し続けています。問題は (どうやら?) ボタンの Click イベント内ではなく、Page_Load 中にのみ EventHandler をフックできることです。
基本的に、ボタンを作成するためのコードがいくつかあります。
private Button CreateButton(string id, string text) {
Button b = new Button();
b.ID = id;
b.Text = text;
b.Command += new CommandEventHandler(Button_Command);
b.CommandArgument = text;
return b;
}
これらの新しいボタンがクリックされると、コマンド引数が渡され、それらのコマンド引数に基づいて新しいボタンが作成されます。
void Button_Command(object sender, CommandEventArgs e) {
//Put code here that creates new buttons based on what's submitted
DoThis(e.CommandArgument.ToString());
}
しかし、ボタンのクリック イベント内でこのコードを実行すると、新しく作成されたボタンの EventHandler が接続されません。
最初にページにアクセスしたときは、テキスト入力と GO ボタンしかありません。コマンド引数とともに一連の新しいボタンを作成する必要があります。
protected void bntGo_Click(object sender, e EventArgs){
DoThis(txtInput.Text);
}
private void DoThis(string arg){
//Do some logic to create a Dictionary<string, int> object (sortedDict)
//based on the arg passed, then for each KeyValuePair in the Dictionary,
//add a button to a panel on the page, setting each button's commandarguments
//to each string in the dictionary
int count=1;
foreach (KeyValuePair<string, int> pair in sortedDict) {
pnlButtonsPanel.Controls.Add(CreateButton("Btn"+count.ToString(), pair.Key));
}
}
どうすればこれを達成できますか? DoThis() は、クリックしたボタンから CommandArguments を渡す必要があるため、ページが読み込まれるたびに DoThis() 関数を実行することはできませんが、これは page_load 内では使用できません。
私は何を間違っていますか?新しいアプローチが必要です。私はここで自分自身を円で考えています。
ありがとう!