我有以下代码:
[WebMethod]
public static string GenerateHtml(string id)
{
//return id;
DataView vwMain2;
try
{
DbProviderFactory dbf = DbProviderFactories.GetFactory();
using (IDbConnection con = dbf.CreateConnection())
{
string sSQL;
sSQL = "select top 20 " + ControlChars.CrLf
+ " ASSISTING_FILE_ID, DATE_ENTERED, CLIENT_CLAIM_NUM, PRIMARY_INSURED, PRIMARY_CLAIMANT, LOB_ID, FILE_STATUS, BRANCH_NAME," + ControlChars.CrLf
+ " OWNERS_FIRST_NAME, OWNERS_LAST_NAME, OWNERS_NAME, OWNERS_EMAIL, OWNERS_OFFICE_PHONE, OWNERS_FAX_PHONE, OWNERS_CELL_PHONE" + ControlChars.CrLf
+ " from vwFILES_DetailViewWithOwners" + ControlChars.CrLf
+ " where 1 = 1 " + ControlChars.CrLf;
//+ " where 1 = 1 and WEB_USER_ID = '" + Security.USER_ID.ToString() + "'" + ControlChars.CrLf;
using (IDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = sSQL;
using (DbDataAdapter da = dbf.CreateDataAdapter())
{
((IDbDataAdapter)da).SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
da.Fill(dt);
vwMain2 = dt.DefaultView;
GridView2.DataSource = vwMain2;
GridView2.DataBind();
}
}
}
}
}
catch (Exception ex)
{
SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex.Message);
//lblError.Text = ex.Message;
}
}
我的ASPX页面中有以下内容:
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
当我尝试在后面的代码中引用GridView2
时,它说:“非静态字段,方法或属性GridView2需要一个对象引用。”
如何解决此问题,以便在调用GenerateHtml
时创建网格视图,或是否有更好的方法?
答案 0 :(得分:3)
调用WebMethod时,您不会引用任何页面元素。请记住,您正在调用静态方法。要访问代码隐藏中的任何页面级元素,您必须通过.NET页面生命周期,在那里发生所有“魔法”。
看看这个问题,找出如何做你想做的事:How to update an datagrid with webmethods