I have the following code behind:
[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;
}
}
I have the following in my ASPX page:
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
When I try to reference GridView2 in my code behind, it says, “An object reference is required for the non-static field, method, or property GridView2.”
How can I resolve this issue so that I can create my grid view when GenerateHtml is called, or is there a better way?
You will not have a reference to any page element when calling a WebMethod. Remember, you are calling a static method. For access to any page-level elements in code-behind you must go through the .NET page lifecyle, where all the “magic” happens.
Take a look at this SO question to find out how to do what you want: How to update an datagrid with webmethods