c#/oop noob here. I am creating a datatable from the schema of a sql server database. I want to have a button that lets the user pick some tables out of this schema and do something (insert rows for example). However, the method is unable to reference the datatable of my first method – how can I reference the datatable made in the first method from another?
Here is the code I am using:
public Form1()
{
/****************************************************************/
string sqlSchema = " SELECT TABLE_CATALOG AS tblname ";
sqlSchema += " , TABLE_SCHEMA AS tblschema ";
sqlSchema += " , TABLE_NAME AS tblname ";
sqlSchema += " , COLUMN_NAME AS colname ";
sqlSchema += " , DATA_TYPE AS DATA_TYPE ";
sqlSchema += " , CHARACTER_MAXIMUM_LENGTH AS colsize ";
sqlSchema += " FROM INFORMATION_SCHEMA.COLUMNS ";
InitializeComponent();
OleDbConnection cn = new OleDbConnection(@"Provider=SQLNCLI;Server=THINK\SQLExpress;Database=Northwind;Trusted_Connection=yes;");
OleDbDataAdapter da = new OleDbDataAdapter(sqlSchema, cn);
DataTable dt = new DataTable();
da.TableMappings.Add("Table","Schema");
da.Fill(dt);
dataGridView1.DataSource = dt;
}
public void sql_PopulateTable(string tablenm, int rows)
{
// error on this line:
DataTable table1 = da.Tables["Schema"];
}
The error I am getting is ‘da’ is not recognized in the current context. Should I be declaring my sqlSchema variable as static? How should I go about doing that syntactically?
Thanks —
Your variables are declared inside the scope of the Form1 constructor – therefore once the constructor has exited, the variables are destroyed.
You need to make a class level property or variable to contain your information so that all methods can access it.