• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2226
  • Last Modified:

convert to C#, viewstate

Hi Expert,

I tried to convert VB.NET to C#, there is one line shown below gives error message when I build the project.  It is viewstate statement, this line works fine in VB.NET.

Cannot implicitly convert type 'object' to 'System.Data.DataTable'

*******************************

DataTable tableSource;
DataTable tableTarget;

private void Page_Load(object sender, System.EventArgs e)
{
            
if (!Page.IsPostBack)
{
tableSource = ds.Tables["tblFromUsers"];
tableTarget = ds.Tables["tblToUsers"];
.......

ViewState["tblSource"] = tableSource;
ViewState["tblTarget"] = tableTarget;                                          
}
else
{
tableSource = ViewState["tblSource"];   <------ Cannot implicitly convert type 'object' to 'System.Data.DataTable'
tableTarget = ViewState["tblTarget"];
}
                  
}
0
5281
Asked:
5281
  • 2
  • 2
1 Solution
 
dstanley9Commented:
use

tableSource = ViewState["tblSource"] as DataTable;  
tableTarget = ViewState["tblTarget"] as DataTable;
0
 
5281Author Commented:
dstanley9,

You are great, that works.  However, I am a little bit confused, why sometimes it need define again, what need redefined, what doesn't need redefined, do we just remember we need define that if it is datatable, dataset?
0
 
dstanley9Commented:
You're not redefining it.  There is not an implicit cast from Object (which ViewState[] returns) to DataTable.  You have to explicitly state what type you want to cast it to.  The "as" keyword is saying "If you can cast it to a DataTable, do it, otherwise give me a null object):

http://msdn2.microsoft.com/en-us/library/cscsdfbt.aspx

0
 
5281Author Commented:
dstanley9,

I think I understand that now.  Thanks again.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now