gpt4 book ai didi

c# - 从 C# 中以编程方式创建的 TextBox 中获取值

转载 作者:行者123 更新时间:2023-12-03 21:37:09 24 4
gpt4 key购买 nike

我遇到了这个令人痒痒的问题,但我无法让代码工作

发布表单时如何从 TextBox 读取值?

一些代码...

protected override void CreateChildControls() {

base.CreateChildControls();

TextBox queryBox = new TextBox();
queryBox.ID = "querybox";
queryBox.ToolTip = "Enter your query here and press submit";
Controls.Add(queryBox);

Button queryButton = new Button();
queryButton.UseSubmitBehavior = false;
queryButton.ID = "querybutton";
Controls.Add(queryButton);

if (Page.IsPostBack == true) {
try {
string query = querybox.Text;

DataGrid dataGrid = new DataGrid();
dataGrid.DataSource = Camelot.SharePointConnector.Data.Helper.ExecuteDataTable(query, connectionString);
dataGrid.DataBind();
Controls.Add(dataGrid);
} catch (Exception a) {
Controls.Add(new LiteralControl(a.Message));
} // try
} // if
} // void

我稍微缩短了代码,但你看到了这个想法,它的字符串 query = querybox.text 不起作用。我尝试过几种不同的变体,即

TextBox querybox = (TextBox)FindControl("querybox");
string query = querybox.Text;

但是没有...

如有任何提示,我们将不胜感激!谢谢

最佳答案

问题在于您的控件未填充 CreateChildControls 中 ViewState 的值。我建议在按钮上使用单击事件处理程序。

更新您的按钮代码:

Button queryButton = new Button();
queryButton.UseSubmitBehavior = false;
queryButton.ID = "querybutton";
queryButton.Text = "Query";
queryButton.Click += new EventHandler(queryButton_Click);
Controls.Add(queryButton);

然后,编写点击事件处理程序:

void queryButton_Click(object sender, EventArgs e)
{
TextBox querybox = this.FindControl("querybox") as TextBox;
try
{
string query = querybox.Text;
DataGrid dataGrid = new DataGrid();
dataGrid.DataSource = Camelot.SharePointConnector.Data.Helper.ExecuteDataTable(query, connectionString);
dataGrid.DataBind();
Controls.Add(dataGrid);
}
catch (Exception a)
{
Controls.Add(new LiteralControl(a.Message));
} // try
}

关于c# - 从 C# 中以编程方式创建的 TextBox 中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4799154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com