problem with getting data from database - c#

I am trying to get the data from database by using the below code.....
if there is no data in the table it will always goes to
this statement
I am using mysql.net connector for getting the data and i am doing winforms applications
using c#
public DataTable sales(DateTime startdate, DateTime enddate)
{
const string sql = #"SELECT memberAccTran_Source as Category, sum(memberAccTran_Value) as Value
FROM memberacctrans
WHERE memberAccTran_DateTime BETWEEN #startdate AND #enddate
GROUP BY memberAccTran_Source";
return sqlexecution(startdate, enddate, sql);
}
and the below code is for return sqlexceution...function..
private static DataTable sqlexecution(DateTime startdate, DateTime enddate, string sql)
{
var table = new DataTable();
using (var conn = new MySql.Data.MySqlClient.MySqlConnection(connectionstring))
{
conn.Open();
var cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
var ds = new DataSet();
var parameter = new MySql.Data.MySqlClient.MySqlParameter("#startdate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter.Direction = ParameterDirection.Input;
parameter.Value = startdate.ToString(dateformat);
cmd.Parameters.Add(parameter);
var parameter2 = new MySql.Data.MySqlClient.MySqlParameter("#enddate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter2.Direction = ParameterDirection.Input;
parameter2.Value = enddate.ToString(dateformat);
cmd.Parameters.Add(parameter2);
var da = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
da.Fill(ds);
try
{
table = ds.Tables[0];
}
catch
{
table = null;
}
}
return table;
}
even if there is no data the process flow will goes to this line
table = ds.Tables[0];
how can i reduce this .....
would any one pls help on this....

In your case if you are think that catch block will get excuted if there is no row available than you are wrong because Even if there is no data once select query is get exucuted without exception it Creates datatable with the columns but with no rows.
for this i think you can make use of ds.table[0].rows.count property which return 0 if there is no row in datatable.
if ( ds.Tables[0].Rows.Count > 0 )
table = ds.Tables[0];
else
table=null;

It returns an empty table. This is common behavior. If you want to have table null you should check for the row count :
If ( ds.Tables[0].Rows.Count >. 0 )
table = ds.Tables[0];
Else
table=0

I'm not really sure what you're asking here ... I assume you want it to skip the table = ds.tables[0] line if there is no data?
if thats the case a try/catch wont work as it wont throw an exception ... try something like this instead ...
if(ds.Tables.Count > 0 && ds.Tables[0].Rows.Count >0)
{
table = ds.Tables[0];
}
else
{
table = null;
}

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.

MaxLength of column seems to be always -1 for the string fields in the datatable C#

All my data table column fields from the stored procedure is string fields as like given below
[Account Code] varchar(10),
Filler1 varchar(5),
[Accounting Period] varchar(7),
[Transaction Date] varchar(8),
Filler2 varchar(2),
[Record Type] varchar(1),
[Source] varchar(2),
[Journal No] varchar(5),
[Journal Line] varchar(7)
Using the below code only I am picking the value from the SP to the dataset as given below
public DataSet InvoicesToSageExtractGoodsIn(string invoiceDateFrom)
{
SqlConnection conn = null;
DALFactory dalFactory = null;
SqlDataAdapter da = null;
try
{
DataSet dsInvoiceCustomer = new DataSet();
dalFactory = new DALFactory();
conn = new SqlConnection(dalFactory.ConnectionStringVI);
conn.Open();
SqlCommand sqlCommand = new SqlCommand("prc_ReturnSageExtractGoodsIn", conn);
sqlCommand.CommandType = CommandType.StoredProcedure;
DALSystemTable dst = new DALSystemTable(this.dao);
sqlCommand.CommandTimeout = Convert.ToInt32(dst.GetSystemConstant("CommandTimeOut"));
SqlParameter param1 = sqlCommand.Parameters.Add("#InvoiceDateFrom", SqlDbType.DateTime);//VI-165
param1.Direction = ParameterDirection.Input;
param1.Value = invoiceDateFrom;
DataSet dsInvoice = new DataSet("VisionInvoicing");
DataTable dtInvoiceNos = new DataTable("tblSageExtractGoodsIn");
da = new SqlDataAdapter(sqlCommand);
da.Fill(dsInvoice);
dsInvoice.Tables[0].TableName = "tblGenerateInvoice";
return dsInvoice;
}
catch (Exception ex)
{
throw new DatabaseException(ex.Message, ex);
}
}
When I try to pick the MaxLength of the column (dtSAGEExtract.Columns[i].MaxLength) from that dataset table it always shows -1 value.
foreach (DataRow drExtract in dtSAGEExtract.Rows)
{
int fieldCount = (dtSAGEExtract.Columns.Count);
for (int i = 0; i < fieldCount; i++)
{
int length = dtSAGEExtract.Columns[i].MaxLength;
writer.Write(drExtract[i].ToString().PadRight(length));
}
writer.WriteLine();
}
writer.Close();
Does anyone have any idea why it is always showing -1 for all the fields?
First you need to add your DataTable to the DataSet to make it work after you created the DataTable because they are not connected in your example and filling the DataSource has no impact on the DataTable created in the next line so that you can use the additional schema information:
dsInvoice.Tables.Add(dtInvoiceNos);
then you need to call the SqlDataAdapter.FillSchema Method on your SqlDataAdapter to get more information from your database then just the data when using only the Fill method
da.FillSchema(dtInvoiceNos, SchemaType.Source);
da.Fill(dsInvoice);
The fill operations must be called after you added the table to the dataset.
It does not represent the MaxLength of DataTable column. It is not depend on database schema either.
It return -1 because it is default value when you do not set anything.
http://msdn.microsoft.com/en-us/library/system.data.datacolumn.maxlength(v=vs.110).aspx
Because you not fill schema to dataset.
Normaly -1 is default length of column.
You should use:
da.FillSchema(dsInvoice, SchemaType.Mapped)
UPDATE:
DataTable dtInvoiceNos = dsInvoice.Tables[0];
Please check: http://msdn.microsoft.com/en-us/library/229sz0y5(v=vs.110).aspx

Get Values from DataTable by row and column name

I'm typically used to traditional table in SQL where I have multiple columns with rows populated. I execute a stored procedure and store all the data in DataTable and loop through the table to get the results I need. For example,
public static DataTable getInfo (string sessionID)
{
try
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SandBox"].ConnectionString);
SqlCommand cmd = new SqlCommand("GetSessionInfo", conn);
cmd.Parameters.AddWithValue("SessionGUID", sessionID);
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
catch (Exception)
{
throw;
}
}
I would load the DataTable:
DataTable infoTbl = new DataTable();
infoTbl = getInfo(lbldatabasesessionID.Text);
And I would use foreach loop to loop through the DataTable.
foreach (DataRow row in infoTbl.Rows)
{
string x = col.ToString();
}
The issue I run into is the database guy gave me a stored procedure that returns a different output (different from what I'm used to). It's a row based.
The only way I can access for example the First Name is if I hard code the position like:
string firstName = infoTbl.Rows[16][2].ToString();
I don't feel comfortable doing this since the position could potentially change. How would I access ElementValue by knowing the name knowing ElementType and ElementName?
Any suggestions?
Using DataSet:
string firstName = string.Empty;
DataRow row = table.Select("ElementType = 'Demographics' AND ElementName = 'FirstName'").FirstOrDefault();
if (row != null)
{
firstName = (string)row["ElementValue"];
}
Using Linq:
string firstName = table.AsEnumerable()
.Where(f => f.Field<string>("ElementType") == "Demographics" &&
f.Field<string>("ElementName") == "FirstName")
.Select(f => f.Field<string>("ElementValue")).FirstOrDefault();

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

Get profile id using username in DB

I have to catch the username entered in the login page and get corresponding profileid(the column in DB) and show it in another page my DAL code is
public DataTable getall()
{
SqlConnection conn1 = Generic.DBConnection.OpenConnection();
DataTable dt=new DataTable();
try
{
string sql = "Select * from Profile_Master";
SqlCommand cmds = new SqlCommand(sql,conn1);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmds);
sqlDa.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
return dt;
}
My UI
DataTable dt1 = new DataTable();
ProfileMasterDAL dal = new ProfileMasterDAL();
dt1 = dal.getall();
if (dt1.Rows.Count > 0)
{
Session["sdds"] = dt1.Rows[0]["FirstName"].ToString();
Session["EmailId"] = dt1.Rows[0]["EmailID"].ToString();
Session["pid"] = dt1.Rows[0]["NewidColumn"].ToString();
Response.Redirect("~/Myhome.aspx");
but i am able to get the first value in the DB not the corresponding value for the username?
Your select statement has 10 rows. and the required row for you is in 5th position.
when you say dt1.Rows[0]["FirstName"] you will get only the first record but not the 5th record.
If you want to make this work, add where condition to your select statement, which returns exactly one required row for you.
something like..
"select * from Profile_Master PM Where PM.UserName = #username"
where #username is your input from login page. And is unique in the database Table

Categories