Returning dataset values giving an error - c#

I have defined the following function which would return 3 columns from table.
public DataSet GetFunc()
{
int iRet = 0;
DataSet ds = new DataSet();
SqlConnection sqlConnection = new SqlConnection();
try
{
iRet = connect(ref sqlConnection);
if (DB_SUCCESS_CONNECT == iRet)
{
SqlCommand sqlCommand = new SqlCommand("", sqlConnection);
String strQuery = "Select ID, Did, FirstName from Users";
sqlCommand.CommandText = strQuery;
SqlDataAdapter adaptor = new SqlDataAdapter(sqlCommand);
adaptor.Fill(ds);
sqlConnection.Close();
return ds;
}
}
catch (Exception e)
{
disconnect(ref sqlConnection);
}
}
But when I'm trying to build it, I'm getting the error:
Error 172 'GetFunc()': not all code paths return a value
I'm confused on where am I going wrong. Can someone guide me through?

In the try block You have given a return type while in the catch block there is no return type.
This error usually occurs when the compiler does not find an appropriate return values.
Try returning ds in catch
But make sure that further in your logic you check ds for a null check

public DataSet GetFunc()
{
int iRet = 0;
DataSet ds = new DataSet();
SqlConnection sqlConnection = new SqlConnection();
try
{
iRet = connect(ref sqlConnection);
if (DB_SUCCESS_CONNECT == iRet)
{
SqlCommand sqlCommand = new SqlCommand("", sqlConnection);
String strQuery = "Select ID, Did, FirstName from Users";
sqlCommand.CommandText = strQuery;
SqlDataAdapter adaptor = new SqlDataAdapter(sqlCommand);
adaptor.Fill(ds);
sqlConnection.Close();
return ds;
}
}
catch (Exception e)
{
disconnect(ref sqlConnection);
}
return null;
}
Not all paths of your code return value, but have to. If DB_SUCCESS_CONNECT!=iRet you won't return result. Try returning some default value, maybe null like above. Another problem is that you are not returning value if exception is thrown. When exception is thrown you are disconnecting and not returning any value.

it is because there is no return path in case :- DB_SUCCESS_CONNECT != iRet

If an exception is being thrown within the try ... catch block there is no return value specified.
Add:
return ds;
at the end of your function after the catch block.

You have only return statements in try block which is not assured that it will always executed due to exception what compiler assumes. Add another return statement that returns null or dataset out of try then you wont get error. You can have only one return statement instead of two or three.
public DataSet GetFunc()
{
int iRet = 0;
DataSet ds = null;
SqlConnection sqlConnection = new SqlConnection();
try
{
iRet = connect(ref sqlConnection);
if (DB_SUCCESS_CONNECT == iRet)
{
SqlCommand sqlCommand = new SqlCommand("", sqlConnection);
String strQuery = "Select ID, Did, FirstName from Users";
sqlCommand.CommandText = strQuery;
SqlDataAdapter adaptor = new SqlDataAdapter(sqlCommand);
ds = new DataSet();
adaptor.Fill(ds);
sqlConnection.Close();
}
}
catch (Exception e)
{
disconnect(ref sqlConnection);
}
return ds;
}

your code fail because you only return value if the condition true. if condition fail or if some exception happen there is nothing returning from your method.
and also please note, you are not handling connection properly. You need to close or dispose connection object. I would change your method as below
public DataSet GetFunc()
{
string strQuery = "Select ID, Did, FirstName from Users";
DataSet ds = new DataSet();
using (var sqlConnection = new SqlConnection())
using (var sqlCommand = new SqlCommand(strQuery, sqlConnection))
using (var adaptor = new SqlDataAdapter(sqlCommand))
{
adaptor.Fill(ds);
}
return ds;
}

Place return statement after try and catch block, try with the code below:
public DataSet GetFunc()
{
int iRet = 0;
DataSet ds = new DataSet();
SqlConnection sqlConnection = new SqlConnection();
try
{
iRet = connect(ref sqlConnection);
if (DB_SUCCESS_CONNECT == iRet)
{
SqlCommand sqlCommand = new SqlCommand("", sqlConnection);
String strQuery = "Select ID, Did, FirstName from Users";
sqlCommand.CommandText = strQuery;
SqlDataAdapter adaptor = new SqlDataAdapter(sqlCommand);
adaptor.Fill(ds);
sqlConnection.Close();
}
}
catch (Exception e)
{
disconnect(ref sqlConnection);
}
return ds;
}
If function has return type it should return something in all the situation, so function should have return value for Try block as well as for Catch block

Related

Don't show insert tile second insert do in localDataBace

I want insert some data to localdatabace and insert is successfully done but don't show in my datagridview tile second insert do for debog it I Call Select All end of my insert and see the last insert don't show in it but whene i insert a next data , last data will be showing can every one help me pleas?
public void connect()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(conString);
String sqll = "Insert into TblBank (txtTodayDate" +
",txtSahebanHesab" +
",txtShobe" +
",txtShomareMoshtari" +
",txtShoareHesab" +
",cmbNoeHesab" +
",txtSarresid" +
")";
try
{
sql.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqll, sql);
SqlCommand sc = new SqlCommand(sqll,sql);
sc.Parameters.AddWithValue("todayDate", new PersianDateTime(dtpTodayDate.the_date).ToString("yyyy/MM/dd"));
sc.Parameters.AddWithValue("sahebanHesab", txtSahebHesabName.Text);
sc.Parameters.AddWithValue("shobe", txtshobe.Text);
sc.Parameters.AddWithValue("shomareMoshtari", txtShomareMoshtari.Text);
sc.Parameters.AddWithValue("shoareHesab", txtShomareHesab.Text);
sc.Parameters.AddWithValue("noeHesab", cmbNoeHesab.SelectedIndex);
sc.Parameters.AddWithValue("sarresid", txtSarResidMah.Text);
sc.ExecuteNonQuery();
sql.Close();
select();
}
catch (Exception ex)
{
}
}
and select is
private void select()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection cn = new SqlConnection(conString);
String sqlString = "SELECT * FROM TblBank Order BY Id desc ";
SqlConnection sql = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sqlString, cn);
try {
sql.Open();
SqlDataAdapter sa = new SqlDataAdapter(sqlString, sql);
using (SqlDataReader read = sa.SelectCommand.ExecuteReader())
{
if (read.Read())
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
sql.Close();
}
catch (Exception ex)
{
}
}
The DataReader.Read() method will iterate result set before DataTable.Load(). Because the DataReader is a forward-only stream, it has empty result set when DataTable.Load() executes and DataTable content is still empty while setting DataSource for DataGridView. Try DataReader.HasRows property to check result set availability:
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlString, cn))
{
try
{
cn.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
// check if the reader returns result set
if (read.HasRows)
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
}
catch (Exception ex)
{
// do something
}
}
}

Asp.net the gridView does not show the row headers

I have this problem,
when the table is empty, the GridView does not show the row headers
i use .net framework 4 and internet Explorer,Can you help me?
this is the code:
this is code
private void loadTCOR27()
{
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
try
{
string sql = null;
gridViewTCOR27.Visible = true;
table1.Visible = false;
string connectionString = SestanteWeb.Global.rCRVigServer.leggiStringaConnessioneSicurezzaSqlClient();
sql = "select * FROM [PUMA2_FINANZIARIAFAMILIARE].[dbo].[TCOR27]";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
// gridView1.DataSource = ds.Tables[0];
gridViewTCOR27.DataSource = ds.Tables[0];
gridViewTCOR27.DataBind();
}
catch (Exception ex)
{
}
finally
{
adapter.Dispose();
}
}
Set the property ShowHeaderWhenEmpty to true in your Gridview declaration. May be it will help you.
Here is the reference to this property.
Ref

How to return default value when value is null or empty

How can I make the below code return zero if the returned value is null or empty. Also how can I return only the first record on the data table
private DataTable GetData(SqlCommand cmd)
{
gridoutofstock.DataBind();
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["AhlhaGowConnString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
You need to use SqlCommand.ExecuteScalar instead of the SqlDataAdapter, you are trying to retrive a single scalar value and not a DataSet.
Example :
static int GetOrderQuantity()
{
int quantity = 0;
string sql = "select sum(Quantity) from [dbo].Orderdetails ";
using (SqlConnection conn = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
quantity = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
//Handle exception
}
}
return quantity;
}

not all code path return value

error: not all code path returns a value,
i'm trying to return a dataset from function but getting this error,
code:
public partial class crystalReport_manual : System.Web.UI.Page
{
String conStr = WebConfigurationManager.ConnectionStrings["LoginDatabaseConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
DataSet1 ds = Dataset_load("Select * from login");
ReportDocument rd = new ReportDocument();
rd.Load(Server.MapPath("CrystalReport.rpt"));
rd.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rd;
}
public DataSet1 Dataset_load(String query)
{
SqlConnection sqlcon = new SqlConnection(conStr);
SqlCommand sqlCom = new SqlCommand("select * from Login", sqlcon);
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom);
// DataSet ds = new DataSet("CRDataSet");
try
{
sqlcon.Open();
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataSet1 ds = new DataSet1();
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
return ds;
}
catch (Exception exc)
{
Response.Write(exc.Message);
}
finally
{
sqlcon.Close();
}
}
What if an exception occur, your catch or finally block should return some value.
Since you are only closing the connection in finally you can use using block like:
public DataSet1 Dataset_load(String query)
{
DataSet1 ds = new DataSet1();
using(SqlConnection sqlcon = new SqlConnection(conStr))
using(SqlCommand sqlCom = new SqlCommand("select * from Login", sqlcon))
using (SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom))
{
try
{
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
return ds;
}
catch (SqlException se)
{
Response.Write(se.Message);
return null;
}
catch (Exception exc)
{
Response.Write(exc.Message);
return null;
}
}
}
using internally translates to try-finally block, and works with those which implements IDisposable, in finally block it calls the Dispose method, since SqlConnection, SqlCommand, and SqlDataAdapter, all implements IDisposable with using statement it will call Dispose at the end which would close the connection.
public DataSet1 Dataset_load(String query)
{
DataSet1 ds = new DataSet1();
using(SqlConnection sqlcon = new SqlConnection(conStr))
using(SqlCommand sqlCom = new SqlCommand("select * from Login", sqlcon))
using (SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom))
{
try
{
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
//return ds;
}
catch (SqlException se)
{
Response.Write(se.Message);
//return null;
}
catch (Exception exc)
{
Response.Write(exc.Message);
//return null;
}
}
return ds;
}
Building off the previous user's response, if an empty DataSet is returned at the end of your using statement, you can always check ds.Tables.Count to see if anything was returned. Otherwise you can use the logic above and null check

How to get data from stored sql procedure in dataset with SqlDataAdapter?

Is this good approach to get data from stored procedure? For example procedure is making select * from base. Here is my code but I need help with dataset and adapter:
public static DataSet Osvezi(string naziv_tablice)
{
SqlCommand cmd = null;
DataSet dataset = null;
SqlConnection konekcija = new SqlConnection(ConfigurationManager.AppSettings["skripta"]);
if (konekcija != null)
{
try
{
if (konekcija.State == ConnectionState.Closed)
konekcija.Open();
cmd = new SqlCommand();
cmd.Connection = konekcija;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Osvezi";
cmd.Parameters.Add(new SqlParameter("#tablica", SqlDbType.Int)).Value = naziv_tablice;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Fill the DataSet using default values for DataTable names, etc
da.Fill(dataset);
return dataset;
}
catch (Exception ee)
{
//Obravnava napak
}
finally
{
konekcija.Close();
konekcija.Dispose();
cmd.Dispose();
}
return dataset;
}
return dataset;
}
Try this one instead:
public static DataSet Osvezi(string naziv_tablice)
{
try
{
using (SqlConnection konekcija = new SqlConnection(ConfigurationManager.AppSettings["skripta"]))
{
konekcija.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = konekcija;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Osvezi";
cmd.Parameters.AddWithValue("#tablica", naziv_tablice??DBNull.Value);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
// Fill the DataSet using default values for DataTable names, etc
DataSet dataset = new DataSet();
da.Fill(dataset);
return dataset;
}
}
}
}
catch (Exception ee)
{
//Obravnava napak
}
return null;
}
Please correct the following.
You don't need to open the connection.
There shouldn't be any command.ExecuteNonQuery.
The parameter in the method is string but the datatype of SqlParameter is SqlDbType.Int.

Categories