Click here to Skip to main content
15,881,413 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I am getting the error as "use of unassigned local variable 'dt'" whenever i am compiling my project. My Code is :
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data;

namespace DAL
{
    public class dbHelper
    {
        SqlConnection SQLConn;
        string connectionstring;
        SqlDataAdapter da;
        public void openconnection()
        {
            connectionstring = "Server=GITTWO-PC\\SQL2008R2;Database=emp;User Id=accpac;Password=super1;";
            try
            {
                SQLConn = new SqlConnection(connectionstring);
                SQLConn.Open();
            }
            catch(Exception ex)
            {
                MessageBox.Show(" Error Connecting to database! - " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void closeconnection()
        {
            SQLConn.Close();
        }
            
        public DataTable getdt(string query)
        {
            openconnection();
            da = new SqlDataAdapter(query, SQLConn);
            DataTable dt;
            da.Fill(dt);
            closeconnection();
            return dt;
        }
    
        public Boolean executequery(String query)
        {
            openconnection();
            SqlCommand com =new SqlCommand(query, SQLConn);
            com.ExecuteNonQuery();
            closeconnection();
            return true;
        }
    }
}
Posted
v3

Instead of
C#
DataTable dt;

Write...
C#
DataTable dt = new DataTable();


As you have not instantiated the DataTable object, that's why it is showing the error.
 
Share this answer
 
Comments
Orcun Iyigun 12-Nov-13 1:28am    
You beat me with a min :)
Local variables aren't initialized. You have to manually initialize them.
On your code in this line change it to the following;
C#
DataTable dt = new DataTable();


Good luck,
OI
 
Share this answer
 
Comments
krish.krish 12-Nov-13 1:32am    
thank u so much

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900