Sorry for the silly question. I just started C# programming. I’ve been researching this for many hours now, and read what I could here. This is seemingly so common, I just do not understand why it does not work. I want to declare a variable in a parent method and change the value in a child class. If this isn’t the way to do it, how can I make methods (even for loops or while loops) that return useful data?
Example 1:
static void Main(string[] args)
{
int rowID;
for (int i = 1; i < 500; i++ )
{
rowID = i;
}
Console.WriteLine(rowID);
}
Example 2:
private void SendButtonClicked(object sender, System.EventArgs e)
{
// finds the first row that has not been sent
int rowID = GetMessageRow();
//then process the row and figure out what stored procedure to run
RunStoredProcedure(rowID);
}
public int GetMessageRow()
// finds the first row that has not been sent
{
int rowID;
// skipping some code
while (drGetMessageRow.Read())
{
// while loop does not understand the variable and errors
rowID = drGetMessageRow.GetInt32(0);
MessageBox.Show("1: RowID is " + rowID.ToString());
}
}
Your GetMessageRow method needs to return rowID. This is what allows rowID (which is a different variable) to have its value set in the SendButtonClicked method.