I want to show next record by clicking a button. Here’s my code
private DataTable GetData()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
SqlCommand sqlCmd = new SqlCommand("Select * From Data", connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
}
catch (System.Data.SqlClient.SqlException ex)
{
}
finally
{
connection.Close();
}
return dt;
}
public Form1()
{
DataTable dt = GetData();
if (dt.Rows.Count > 0)
{
// Populate the TextBox with the first entry on page load
txtName.Text = dt.Rows[0]["Name"].ToString();
}
}
but i am getting an exception on txtName.Text = dt.Rows[0][“Name”].ToString();
Object Reference is not set of an object.
Please help me
Add in
nullchecks fortxtNameanddt.Rows[0]["Name"]:If
dt.Rows[0]["Name"]is null, it is null in the Database. If that is not expected, debug your database insertion code.If
txtNameis null, it is because you are executing this code beforetxtNamehas been initialized. Make sure your code does not execute until aftertxtNamehas been initialized.