在我的Default.aspx.cs代码隐藏中,我填充了一个DataTable _dt,其中包含从制表符分隔的文本文件中读取的数据。我想在用户单击Default.aspx上的按钮时向用户显示_dt的所有内容。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Net;
using System.Text;
using System.Data;
using System.IO;
...
String strLine = String.Empty;
Int32 iLineCount = 0;
System.IO.StreamReader srdr = new System.IO.StreamReader(filePath);
do
{
strLine = srdr.ReadLine();
if (strLine == null)
{ break; }
if (0 == iLineCount++)
{
_dt = this.CreateDataTableForTabbedData(strLine);
}
this.AddDataRowToTable(strLine, _dt);
}
while (true);
form1.Controls.Add(_dt);
但是VS给了我错误:“当前上下文中不存在名称form1”。 form.1在Default.aspx中不存在,但它确实存在于Site.Master中。
我意识到我可能需要在Default.aspx中存在form1以便我的代码隐藏工作,但如果我尝试这样做,并将Site.master中的ID更改为form2,我会收到错误 “一个页面只能有一个服务器端的Form标签。”我必须在Site.Master上保留表单,但我不能将生成表的代码隐藏移动到Site.Master.cs
答案 0 :(得分:0)
页面控件(在你的情况下是this或this.Page)有一个对Master本身的引用,所以你必须遍历控件集合以找到Master的子控件 - 其中一个将是表单。它不能保证是独一无二的,它显然是M * N的顺序,但它长期为我做了诀窍。
你会像这样使用它:
控制oCtl = SomeUtilityClass.FindControlRecursive(this.Page,“form1”); (记得在这里检查空值; - )
我写这篇文章来处理这样的事情:
/// <summary>
/// Recursive loop to find a control
/// </summary>
/// <param name="rootCtl">Control whose control collection we will begin traversing in search of the
/// given ID</param>
/// <param name="Id">ID to search for</param>
/// <returns></returns>
public static Control FindControlRecursive(Control rootCtl, string desiredCtlID)
{
//Make sure this thing exists
if (rootCtl == null)
return null;
//See if it's the one we're after
if (rootCtl.ID == desiredCtlID)
return rootCtl;
//Make sure it has controls to loop over
if (!rootCtl.HasControls())
return null;
foreach (Control oCtl in rootCtl.Controls)
{
Control FoundCtl = FindControlRecursive(oCtl, desiredCtlID);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
答案 1 :(得分:0)
我能够在OleDbDataAdapter上使用this tutorial显示我的数据。
DataSet dataset = Read_File_Into_Dataset("C:\\TEMP\\", "input.txt");
DataGrid dg = new DataGrid();
dg.DataSource = dataset;
dg.DataBind();
this.Controls.Add(dg);
public DataSet Read_File_Into_Dataset(string fullpath, string file)
{
string sql = "SELECT * FROM `" + file + "`"; // Read all the data
OleDbConnection connection = new OleDbConnection // Connection
("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullpath + ";"
+ "Extended Properties=\"text;HDR=YES;FMT=Delimited\"");
OleDbDataAdapter ole = new OleDbDataAdapter(sql, connection); // Load the data into the adapter
DataSet dataset = new DataSet(); // To hold the data
ole.Fill(dataset); // Fill the dataset with the data from the adapter
connection.Close(); // Close the connection
connection.Dispose(); // Dispose of the connection
ole.Dispose(); // Get rid of the adapter
return dataset;
}