Assign DataSet to Local Variables - c#

I am running a SQL Query and returning a DataSet - I want to iterate the info in the DataSet and assign the values to local variables. I have confirmed that my DataSet returns rows but my variables are not getting assigned for some reason. Can someone look at my syntax and assist with why this is occurring?
protected void GetSomeData()
{
string employeeid = this.txtemployeeid.Text;
DataSet empinfo = new DataSet();
empinfo = RunSqlQuery(employeeid);
this.txtemployeefirstname = empinfo.Tables[0].Rows[0]["employeefirstname"].ToString());
this.txtemployeelastname = empinfo.Tables[0].Rows[1]["employeelastname"].ToString());
this.txtemployeeaddress = empinfo.Tables[0].Rows[2]["employeeaddress"].ToString());
this.txt.employeephone = empinfo.Tables[0].Rows[3]["employeephone"].ToString());
}
public DataSet RunSqlQuery(string employeeid)
{
string sqlQuery = "Select employeefirstname, employeelastname, employeeaddress, employeephone from abcd where employeeid = "+employeeid+" and employeeid is not null";
try
{
connectionString = System.Configuration.ConfigurationManager.AppSettings[connectionString].ToString();
sqlDatabaseConnection = new SqlConnection(connectionString);
sqlCommand = new SqlCommand(sqlQuery, sqlDatabaseConnection);
sqlDatabaseConnection.Open();
sqlCommand.CommandTimeout = 0;
dataSet = new DataSet();
sqlDataAdapter = new SqlDataAdapter(sqlCommand);
sqlDataAdapter.Fill(dataSet, "Data");
return dataSet;
}
catch (Exception exception)
{
throw exception;
}
finally
{
sqlDatabaseConnection.Close();
sqlCommand.Dispose();
sqlDataAdapter.Dispose();
}
}
EDIT
By variables not getting assigned, I mean when I step through my code, it seems that the value returned from the database is not being populated into the empinfo.Tables[0].Rows[0]["employeefirstname"].ToString()); they are always null.

You're assigning the value to the textbox (at least, I assume txtemployeefirstname is a textbox). I think you mean txtemployeefirstname.text?

Related

DataTable Rows Count Null Exception

Im trying to fill a listview with data from my database but get a null reference exception when i load the listview. Im using MVC pattern.
Code in my data acces layer:
public List<Menu_Item> DB_Get_All_MenuItems()
{
string query = "SELECT * FROM [Menu_Items]";
SqlParameter[] sqlParameters = new SqlParameter[0];
return ReadTables(ExecuteSelectQuery(query, sqlParameters));
}
private List<Menu_Item> ReadTables(DataTable dataTable)
{
List<Menu_Item> menu_items = new List<Menu_Item>();
foreach (DataRow dr in dataTable.Rows)
{
Menu_Item menu_Item = new Menu_Item()
{
Menu_ID = (int)dr["Menu_ID"],
Naam = (string)dr["Naam"],
Prijs = (float)dr["Prijs"],
Voorraad = (int)dr["Voorraad"],
Categorie_ID = (int)dr["Catogorie_ID"]
};
menu_items.Add(menu_Item);
}
return menu_items;
}
I have checked and my SQL parameters are all spelled correctly
The exact error is: datatable.rows = 'datatable.rows' threw an exception of type 'system.nullreferenceexception'
My DateTable method looks like this
protected DataTable ExecuteSelectQuery(string query, params SqlParameter[] sqlParameters)
{
SqlCommand command = new SqlCommand();
DataTable dataTable;
DataSet dataSet = new DataSet();
try
{
command.Connection = OpenConnection();
command.CommandText = query;
command.Parameters.AddRange(sqlParameters);
command.ExecuteNonQuery();
adapter.SelectCommand = command;
adapter.Fill(dataSet);
dataTable = dataSet.Tables[0];
}
catch (SqlException e)
{
return null;
throw new Exception(e.ToString());
}
finally
{
CloseConnection();
}
return dataTable;
}
Check whether dataTable null or not
if(dataTable!=null && dataTable.Rows.Count > 0)
{
foreach (DataRow dr in dataTable.Rows)
{
Menu_Item menu_Item = new Menu_Item()
{
Menu_ID = (int)dr["Menu_ID"],
Naam = (string)dr["Naam"],
Prijs = (float)dr["Prijs"],
Voorraad = (int)dr["Voorraad"],
Categorie_ID = (int)dr["Catogorie_ID"]
};
menu_items.Add(menu_Item);
}
}
check if the datarows.count is null or not ...
Also in DB_Get_All_MenuItems() mention dbconnction string, sql command type, and datareader and all...first make sure the datas is returning in this function o/p....
You are trying to use something that is null. This means you either set it to null, or you never set it to anything at all.
Now, You can then place a breakpoint at every found location and run your program with the debugger attached. Every time the debugger breaks on such a breakpoint, you need to determine whether you expect the reference to be non-null.

display data to listbox C#

Listbox does not show data. Verified data is in database and I am not getting an
error. Not sure where/what is wrong. Thanks in advance. My code is attached.
private void UpDateList()
{
// add data connection and fill data set.
SqlConnection conn = new SqlConnection(dataSource);
DataTable dt = new DataTable();
string sqlString = "select * from Suppliers";
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = sqlString;
da.Fill(ds);
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
foreach(DataRow dRow in ds.Tables[0].Rows)
{
ArrayList values = new ArrayList();
foreach(object value in dRow.ItemArray)
{
values.Add(value);
_Suppliers.Add(values);
}
}
lstSuppliers.DataSource = _Suppliers;
lstSuppliers.Update();
}
It's kinda pointless to enumerate one bindable data collection and transfer data into another bindable collection so it can be bound. Just have your list use the default view of the datatable that already holds the data (allows sorting, filtering etc)
E.g.
LstSuppliers.DataSource = ds.Tables[0].DefaultView;
LstSuppliers.DisplayMember = "column name goes here of what to show eg SupplierName";
LstSuppliers.ValueMember = "column whose value to use for lstSuppliers.SelectedValue e.g. supplierId";
And then for example, not required but an example possibility:
ds.Tables[0].DefaultView.Sort = "[SupplierName] ASC";

Stored procedure returns no rows with SqlDataAdapter

I'm new to using SqlDataAdpter and I'm trying to execute a stored procedure. The stored procedure executes successfully but no rows are returned. I've used SQL Server Profiler to monitor the call and it runs successfully (I can copy and execute the query from profiler without modifying it and get results).
I have the following:
public ActionResult Index()
{
SqlConnection conn = null;
DataSet results = null;
try
{
string connectionString = // ... my connection
conn = new SqlConnection(connectionString );
string query = #"usp_mySP";
conn.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter(query, conn);
sqlAdpt.SelectCommand.CommandType = CommandType.StoredProcedure;
var dataDate = new SqlParameter { ParameterName = "#DataDate", Value = DateTime.Now };
var idList = new SqlParameter { ParameterName = "#IDList", Value = "1231,2324,0833" };
sqlAdpt.SelectCommand.Parameters.Add(dataDate);
sqlAdpt.SelectCommand.Parameters.Add(idList);
results = new DataSet();
sqlAdpt.Fill(results);
sqlAdpt.Dispose();
}
catch (SqlException e)
{
throw new Exception("Exception:" + e.Message);
}
finally
{
if (conn != null)
conn.Close();
}
return View(results);
}
When I inspect the DataSet through the debugger, it always returns 0 rows.
Please help with what I'm doing wrong?
Note: I've also tried (but do NOT prefer) executing as a SQL command:
EXEC usp_mySP #DataDate, #IDList
and it didn't work either as I got int to varchar conversion errors.
I think you try to add SqlParameter using SqlCommand like this :
SqlCommand cmd = new SqlCommand();
cmd.parameter.addwithvalue(#DataDate,DateTime.Now);
So the reason was because of set nocount on. I added it to my sp and it works. Thank you everyone for clarifying.

Convert dataset into integer

look i have this code:
private void obtengoUltimoComienzoColocado()
{
ManejoUsuarios lAdm = new ManejoUsuarios();
lblTodoOK.Text = lAdm.LevantoUltimoIDBarco().ToString();
}
public int LevantoUltimoIDBarco()
{
ConexionBD lP = new ConexionBD();
try
{
string lQuery = "Select Max(idBarco) as UltimoID From Comienzos;";
Convert.ToInt32(lP.ObtenerRegistro(lQuery));
return 1;
}
catch (Exception ex)
{
return 0;
}
}
public DataSet ObtenerRegistro(string SqlQuery)
{
DataSet lResult;
SqlConnection lSqlConnection = new SqlConnection("Data Source=SEBA-PC\\sqlexpress;Initial Catalog=Batalla_Naval;Integrated Security=True");
SqlCommand lSqlCommand = null;
try
{
lSqlCommand = new SqlCommand();
lSqlCommand.CommandText = SqlQuery;
lSqlCommand.CommandType = CommandType.Text;
SqlDataAdapter lAdapter = new SqlDataAdapter(lSqlCommand);
lResult = new DataSet();
lSqlConnection.Open();
lSqlCommand.Connection = lSqlConnection;
lAdapter.Fill(lResult);
}
catch (Exception)
{
throw;
}
finally
{
lSqlConnection.Close();
}
return lResult;
}
As you can see i use three functions to go to the database and get the max ID from the table Comienzos, but when i want to convert the data set to int32 the function LevantoUltimoIDBarco returns me 0,
You have to select the first value from the dataset, you can not convert a complete dataset to integer:
Convert.ToInt32(lP.ObtenerRegistro(lQuery).Tables[0].Rows[0][0]);
or simpler (since the query returns an integer in the dataset):
(Int32)(lP.ObtenerRegistro(lQuery).Tables[0].Rows[0][0]);
And then you have to return or save the result instead of just returning 1.
My friend you should use ExecuteScalar to return a single value, and not an adapter and fill a dataset.
SqlConnection lSqlConnection = new SqlConnection("Data Source=SEBA-PC\\sqlexpress;Initial Catalog=Batalla_Naval;Integrated Security=True");
SqlCommand lSqlCommand = null;
try
{
lSqlCommand = new SqlCommand();
lSqlCommand.CommandText = SqlQuery;
lSqlCommand.CommandType = CommandType.Text;
var result = lSqlCommand.ExecuteScalar();
int MyID = Convert.ToInt32(result);
}
catch(ex)
{
// DO SOMETHING
}
Looking at how you retrieve your data, then the correct code to read that integer (MAX()) is the following
string lQuery = "Select Max(idBarco) as UltimoID From Comienzos;";
DataSet ds = lP.ObtenerRegistro(lQuery);
return Convert.ToInt32(ds.Tables[0].Rows[0][0] == DBNull.Value ? 0 : ds.Tables[0].Rows[0][0]);
However, if your table has no record the MAX(idBarco) will return DBNull as result

Cannot find table 0 in dataset using stored procedures

I am not getting filled dataset after executing a stored procedure.
protected void btnsub_Click(object sender, EventArgs e)
{
ArrayList arInsert = ReturnParameter_insert();
DataSet dsInsertProfile = objadmin.GetGridData(arInsert, objconstant.sSP_INSERT_PROFILE);
if(int.Parse(dsInsertProfile.Tables[0].Rows[0].ItemArray[0].ToString())== 0)
{
lblThank.Text = "Your profile have been successfully saved.";
}
else
{
lblThank.Text = "Your profile is not saved, please try again later.";
}
}
public ArrayList ReturnParameter_insert()
{
ArrayList arProfile = new ArrayList();
Object[] c_first_name = new object[3] { "#strFname", "Varchar", (txtfname.Text != "") ? txtfname.Text : "" };
arProfile.Add(c_first_name);
return arProfile;
}
public DataSet GetGridData(ArrayList dbArray, string sSpName)
{
DataSet dsDataSet = new DataSet();
dsDataSet = datamanager.GetGridData(dbArray, sSpName);
return dsDataSet;
}
public static SqlDbType GetSqlDataType(string sDataType)
{
return (sDataType == "Integer") ? SqlDbType.Int : (sDataType == "Varchar") ? SqlDbType.VarChar : (sDataType == "Date") ? SqlDbType.Date : SqlDbType.BigInt;
}
public static DataSet GetGridData(ArrayList dbArray, string sSpName)
{
DataSet dsDataSet = new DataSet();
SqlConnection cn = createConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sSpName;
object objPrMtrName;
object objSqlType;
object objPrMtrVal;
int i;
for (i = 0; i < dbArray.Count; i++)
{
objPrMtrName = ((object[])(dbArray[i]))[0];
objSqlType = ((object[])(dbArray[i]))[1];
objPrMtrVal = ((object[])(dbArray[i]))[2];
cmd.Parameters.Add(objPrMtrName.ToString(), GetSqlDataType(objSqlType.ToString())).Value = objPrMtrVal;
}
cmd.Connection = cn;
try
{
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dsDataSet);
return dsDataSet;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cn.Close();
cn.Dispose();
}
}
My stored procedure:
CREATE Procedure spInsert_profile
(#strFname varchar(200))
AS
BEGIN
INSERT INTO gdt_Users([c_first_name], [d_modified_dttm], [d_created_dttm])
VALUES(#strFname, GETDATE(), GETDATE())
END
Here I am using 3 tier, the same methods are working successfully for other pages but not for this particular code. The dataset in GETGRIDDATA method is filling null value. I am not able to find. Please help me....
you performing insert operation in your procedure than how is going to return to data Insert into statement does insert operation not retrieve operation.
...To retrieve data you need to call procedure with select * statement.
There is no select statement in your stored proc. adapter.fill() should recieve some sort of table from the stored proc's output.
From what I can see here you are executing a stored procedure that only performs an INSERT command, The reason you are getting a NULL value back is because a non query command such as UPDATE or INSERT will generally return only the number of rows affected e.g. 1 and not the data of the table you inserted to.
You would need to perform a SELECT command after the insert to get any data back.
The problem is in your stored procedure... you have to add select statement to the stored procedure for your return result in DataSet
Because you use Insert Into in your stored procedure.
Access based on Tables property:
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dsDataSet);
var table1 = dsDataSet.Tables[0];
var table2 = dsDataSet.Tables[1];
Link : http://msdn.microsoft.com/fr-fr/library/system.data.dataset.tables.aspx

Categories