我正在使用舊的asp.net web應用程序,並且遇到了嘗試將文本寫入另一個線程的引導文本框的問題。我已經簡化了網絡應用程序轉換的代碼如下所示:從另一個線程/類寫入文本框
Default.aspx.cs:
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using AspNet;
namespace ProblemApp
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
if (this.TextBox1.Text == "")
{
TextBox1.Text = "TEST";
}
}
protected void UpdateButton2_Click(object sender, EventArgs e)
{
AutoLogControl NewAutoLogger = new AutoLogControl();
Thread AutoLoggerThread = new Thread(() => NewAutoLogger.StartAutoLogger(sender));
AutoLoggerThread.Start();
}
}
}
Autolog.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;
namespace ProblemApp
{
public partial class AutoLogControl : _Default
{
public void StartAutoLogger(object sender)
{
//would normally listen for a condition to be met, but for
//this example, just set the Textbox. This is where my issue
//is. TextBox is null.
TextBox1.Text = "TEST 2";
}
}
}
正如你所看到的,我需要設置來自StartAutoLogger()的TextBox,但是當我嘗試時我得到一個空引用。我嘗試了其他幾種解決方案,例如在_Default中創建一個公共方法來設置文本,但這也不起作用。如果你需要它們,這裏是支持文件。
的Default.aspx:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ProblemApp._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="row panel-body verticle-align">
<div class="col-lg-3">
<h4><span class="label label-default"> Text Box : </span></h4>
</div>
<div class="col-lg-9">
<asp:TextBox ID ="TextBox1" name="Textbox1" runat="server" Width="100%" />
</div>
</div>
<div class="row btn-block panel-body">
<div class="col-lg-4">
<asp:Button ID="UpdateButton" runat="server" OnClick="UpdateButton_Click" Text="Update" CssClass="btn btn-default" />
</div>
<div class="col-lg-4">
<asp:Button ID="UpdateButton2" runat="server" OnClick="UpdateButton2_Click" Text="Update 2" CssClass="btn btn-default" />
</div>
</div>
</asp:Content>
Default.aspx.designer.cs:
namespace ProblemApp {
public partial class _Default {
protected global::System.Web.UI.WebControls.TextBox TextBox1;
protected global::System.Web.UI.WebControls.Button UpdateButton;
protected global::System.Web.UI.WebControls.Button UpdateButton2;
}
}
您可以將ID「TextBox」更改爲不同的內容並添加具有更好命名的名稱屬性 –
爲了清晰起見進行了更新。 – user7991682