Im having a bit of an issue with public -v- private variables and scope.
Here is my code
private void PopulateCaseViewer(string paramField, string paramValue)
{
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
if (paramField == "load")
{
string sqlStat = "SELECT c.CaseNo, c.Claimant, c.Defendant, c.DOA, c.CaseType, c.CaseManager, c.Occupation, c.DateInstruction " +
"a.IPName, a.IPRegion, l.IPReference " +
"FROM tblCases AS c INNER JOIN tblIPLinks as l ON c.CaseNo = l.CaseNo " +
"JOIN tblIPAddresses AS a ON l.IPID = a.IPID;";
}
using (linkToDB)
using (var adapter = new SqlDataAdapter(sqlStat, linkToDB))
{
var table = new DataTable();
adapter.Fill(table);
dataCaseViewer.DataSource = table;
}
}
The issue is, that the string sqlStat in the line “using (var adapter = new SqlDataAdapter . …)” states that sqlStat does ‘not exist in the current context’.
I aim to add many IF statements on this method depending on the paramField and paramValues that are passed to it, in order to build different sqlStats to populate dataCaseViewer.DataSource dependent on User input. But if the sqlStat variale from the IF statements can’t be seen by the subsequent call in the SqlDataAdapter then I’m a bit stuck.
Any advice please.
That’s because you defined sqlStat inside the IF statement above it, and that makes it valid only within that statement.
Define sqlStat above the IF, set it inside the IF, and it should work just fine.