Quote:
SqlDataAdapter da1 = new SqlDataAdapter("SELECT Option" + dt.Rows[0]["Opt_Selected"].ToString() + " FROM " + sub + " WHERE Id=" + dt.Rows[0]["Que_Id"].ToString(), con);
DataTable dt1 = new DataTable();
da1.Fill(dt1);
Label2.Text = dt1.Rows[0]["Option" + dt.Rows[0]["Opt_Selected"].ToString()].ToString();
Your code needs some clean up. First off, make it a habit to put objects that eat resources such as
SqlConnection
,
SqlCommand
and
SqlDataAdapter
within a
using statement
to ensure that objects will be properly disposed and closed after they are used.
Second, appending the values directly to your SQL query is a BIG no no as it can potentially leads to SQL Injection attack. Use parameterize query to avoid that to happen:
Protect Your Data: Prevent SQL Injection[
^]
Third, create a common method for getting the data instead of doing the same code that does the same job.
For example you could create a common and reusable method that returns a
DataTable
like this:
public DataTable GetData(string param1, string param2){
DataTable dt = new DataTable();
string sqlStatement = "SELECT ColumnName FROM YourTableName WHERE ColumnName = @Param1 AND ColumnName = @Param2";
using(SqlConnection connection = new SqlConnection(GetConnectionString())){
using(SqlCommand cmd = new SqlCommand(sqlStatement ,connection)){
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Param1", param1);
cmd.Parameters.AddWithValue("@Param2", param2);
using(SqlDataAdapter da = new SqlDataAdapter(cmd)){
da.Fill(dt);
}
}
}
return dt;
}
Fourth, doing a simple calculation is pretty much easy. You just need to understand what you are doing and start from that. You're the only one who can do it because you are the one who knows the formula.
Finally, use the debugger if you are not getting the output that you are expecting. Set a break point in the method where you want to look into and step into each line to figure out what's going on. See,
Navigate code with the Visual Studio debugger - Visual Studio | Microsoft Docs[
^]