Datatable error in c# - c#

I used a datatable for fetching some data from mysql db,my error is
not all code paths return a value
ie return DS.Tables[0] is unable to access inside a loop or if statement.How can i solve this issue?
public DataTable GetAlltheatredet()//I got error here//
{
DataTable myalltheat = GetAllmytheatdet();
foreach (DataRow drow1 in myalltheat.Rows)
{
usermsterid = drow1["UserMasterId"].ToString();
if (usrmid == usermsterid)
{
flag = 1;
break;
}
if (flag == 1)
{
try
{
string connString = "Server=localhost;database=Mytable;uid=root;";
string query = "SELECT * FROM `Mytable`.`Mydata`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(DS);
return DS.Tables[0];
}
catch (MySqlException e)
{
throw new Exception(e.Message);
}
}
}
}

you have if(flag==1) { ... return ... } you need to add an else statement with either a return or a throw new ...
public DataTable GetAlltheatredet()//I got error here//
{
DataTable myalltheat = GetAllmytheatdet();
foreach (DataRow drow1 in myalltheat.Rows)
{
usermsterid = drow1["UserMasterId"].ToString();
if (usrmid == usermsterid)
{
flag = 1;
break;
}
if (flag == 1)
{
try
{
string connString = "Server=localhost;database=Mytable;uid=root;";
string query = "SELECT * FROM `Mytable`.`Mydata`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(DS);
return DS.Tables[0];
}
catch (MySqlException e)
{
throw new Exception(e.Message);
}
}
else {
throw new Exception("Flag isn't 1 and I don't know what to do");
}
}
}

that's a well known error, if your method that return DataType have any multi path blocks like if {} else {} or switch case, you should return something in every path of them.

Related

How can I return/How can I convert dataset to a list of objects (List<ComponenetData>) in C#?

How can I return/How can I convert dataset to a list of objects (List) in C#?
public static DataSet GetComponentData(int CustomerId, int UserId)
{
string connectionString = ConfigurationReader.ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand command = new SqlCommand("GetComponentData", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#CustomerID", SqlDbType.Int).Value = CustomerId;
command.Parameters.Add("#UserId", SqlDbType.Int).Value = UserId;
da.SelectCommand = command;
try
{
da.Fill(ds);
connection.Close();
return ds;
}
catch (Exception ex)
{
string strError = ex.ToString();
return ds = null;
}
finally
{
da = null;
command = null;
connection.Close();
}
}
}
I need to return the result as a list eg.List. I have done this by :
public static string GetGenericListData(string folderName, int CustomerId)
{
//--------------------------------------------------------
// List<Device>lstDevices=new List<Device>();
Devices lstDevices = new Devices();
DataSet ds=new DataSet();
try
{
ds = GetComponentData(CustomerId, UserId);
if(ds.Tables[0].Rows.Count >0)
{
foreach(DataRow dr in ds.Tables[0].Rows)
{
Device _PptDevices=new Device();
_PptDevices.Country = ((dr["Country"]) != null) ? Convert.ToString(dr["Country"]) : "";
_PptDevices.Area = ((dr["Area"]) != null) ? Convert.ToString(dr["Area"]) : "";
_PptDevices.Branch = ((dr["Branch"]) != null) ? Convert.ToString(dr["Branch"]) : "";
_PptDevices.SalesOffice = ((dr["Sales Office"]) != null) ? Convert.ToString(dr["Sales Office"]) : "";
_PptDevices.CustomerNumber = ((dr["Customer Number"]) != null) ? Convert.ToString(dr["Customer Number"
lstDevices.Add(_PptDevices);
_PptDevices = null;
}
}
}
catch
{
}
finally
{
}
string strStatus = "";
if (lstDevices.Count > 0)
{
string FilePath = ConfigurationReader.FileLocation;
XmlSerializer serializer = new XmlSerializer(typeof(Devices));
MemoryStream memStream = new MemoryStream();
serializer.Serialize(memStream, lstDevices);
FileStream file = new FileStream (folderName "\\ComponentData.xml", FileMode.Create, FileAccess.ReadWrite);
memStream.WriteTo(file);
file.Close();
strStatus = "1"; //Success
}
else
{
strStatus = "0"; //Failure
}
return strStatus;
}
Here what I am doing is getting dataset from one function and converting it as a list using another function. Is there any direct method to convert dataset to list more easier? Or how can we assign the result set directly to the list..
Is there any other simple solution?
Let the Student be the class, then you can do something like the following:
dTable = ds.Tables[0];
List<Device> studentList=dTable.AsEnumerable().Select(x => new Device() {
Country =x["column_id"]!=null?x.Field<string>("column_id"):"",
Area = x["Area"]!=null?x.Field<string>("Area"):""
Branch = x["Branch"]!=null?x.Field<string>("Branch"):"",
SalesOffice = x["Sales Office"]!=null?x.Field<string>("Sales Office"):"",
CustomerNumber = x["Customer Number"]!=null?x.Field<string>("Customer Number"):""
}).ToList();
You don't even need to convert it to DataSet if you are interested in List<>, you could directly convert it from reader.
var reader = command.ExecuteReader();
var list = reader.Select(r => new Propertyclass() // specify the class name
{
Id = r["id"] is DBNull ? null : r["id"].ToString(),
Name = r["name"] is DBNull ? null : r["name"].ToString()
})
.ToList();

Error 3 'Survey.fillmydropdownlist()': not all code paths return a value

Thanks, i need some help, and theres error for DBOperation dbo = new DBOperation(); which they say type or namespace cannot be found.
public partial class Survey : System.Web.UI.Page
{
public DataTable fillmydropdownlist()
{
DataTable drpdt = new DataTable();
SqlConnection con= new SqlConnection();
try
{
con.ConnectionString = #"SurveyFdBk_DB";
con.Open();
string q = "SELECT * FROM [Survey]";
SqlCommand cmd = new SqlCommand(q,con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
return drpdt;
}
catch { }
finally{ con.Close(); }
}
protected void Page_Load(object sender, EventArgs e)
{
DBOperation dbo = new DBOperation();
DataTable dt = new DataTable();
dt = dbo.fillmydropdownlist();
DataTable drpdt= new DataTable();
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = drpdt;
DropDownList1.DataTextField="SurveyName";
DropDownList1.DataValueField="SurveyID";
DropDownList1.DataBind();
}
}
}
All the paths of execution must return something. In your method above there are 2 paths:
public DataTable fillmydropdownlist()
{
try
{
//path 1
return drpdt;
}
catch
{
//path 2
return null; //need return value here
}
}
In the event of an exception being thrown you need to return some sort of value, perhaps null?
That being said catching all errors with no logging or handling is not an advisable practice. You should consider adding some error handling and you should dispose of your DataAdapter in your finally block as well.

Crystal report viewer giving me error : "Invalid Argument provided. Failed to open a rowset."

i am having a crystal report , that is to be filled with stored procedure, but when i put any parameter of procedure in .rpt file it is giving me error like
"Invalid Argument provided. Failed to open a rowset."
my code is as below :
public void GroupwiseRegistrationReport()
{
SqlConnection connection;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
connection = gen.con;
string SP = "";
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction = null;
try
{
connection.Open();
transaction = connection.BeginTransaction();
if (rblReportFrom.SelectedValue == "0")
{
SP = "SPGroupwiseIndustriesEM1Report";
}
else
{
SP = "SPGroupwiseIndustriesEM2Report";
}
ValueData = new ArrayList();
ParameterData[0] = "#fromdate";
ValueData.Add(txtTotalBetweenFrom.Text.ToString().Trim());
ParameterData[1] = "#todate";
ValueData.Add(txtTotalBetweenTo.Text.ToString().Trim());
ds = gen.FunSearch_Trans(ParameterData, ValueData, SP, transaction, command);
dt = ds.Tables[0];
if (ds.Tables[0].Rows.Count > 0)
{
if (rblReportFrom.SelectedValue == "0")
{
repdoc.Load(Server.MapPath("~\\admin\\Reports\\Groupwise-EM-I-Registration-Report.rpt"));
}
else
{
repdoc.Load(Server.MapPath("~\\admin\\Reports\\Groupwise-EM-II-Registration-Report.rpt"));
}
repdoc.SetDataSource(ds.Tables[0]);
configureCrystalReports();
crvMSMEReportViewer.ReportSource = repdoc;
//Response.Buffer = true;
//Response.ClearContent();
//Response.ClearHeaders();
//repdoc.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Exported Report");
tablereportviewer.Visible = true;
}
else
{
tablereportviewer.Visible = false;
message("No Records Found.");
}
transaction.Commit();
}
catch (Exception ex)
{
tablereportviewer.Visible = false;
error.LogError(ex);
transaction.Rollback();
}
finally
{
connection.Close();
}
}
Am i missing something or what i cant figure it out please help me..
And which is the best way to deal with crystal report ,is it with using dataset or directly stored proceure?
Update
i changed my code like below but now is giving me message like :"Missing parameter values.
". but i have only two parameter to pass which are "#fromdate" and "#todate"
here is a code snippet :
doc = new ReportDocument();
doc.Load(Server.MapPath("~\\admin\\Reports\\Groupwise-EM-II-Registration-Report.rpt"));
doc.SetDatabaseLogon(ConfigurationManager.AppSettings["userName"], ConfigurationManager.AppSettings["pwd"], ConfigurationManager.AppSettings["serverName"], "databaseName", false);
doc.SetParameterValue("#fromdate", txtTotalBetweenFrom.Text.ToString());
doc.SetParameterValue("#todate", txtTotalBetweenTo.Text.ToString());
crvMSMEReportViewer.ReportSource = doc;
crvMSMEReportViewer.RefreshReport();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ReportDataSet"] != null)
{
crvAccountReportParameter.ReportSource = (ReportDocument)Session["ReportDataSet"];
}
}
private void LoadReport()
{
doc = new ReportDocument();
DataSet dsData = null;
dsData = objAccountReportBAL.getAccountRegister(txtTotalBetweenFrom.Text.ToString(), txtTotalBetweenTo.Text.ToString());
doc.Load(Server.MapPath("CrSalesReport.rpt"));
doc.SetDataSource(dsData.Tables[0]);
Session["ReportDataSet"] = rptDoc;
crvAccountReportParameter.ReportSource = rptDoc;
crvAccountReportParameter.DataBind();
}

How can I query datetime in SQLite database

Here is my code:
string sql = string.Format("select * from StockInTb ");
DataTable dt = dataAccess.GetDataTable(sql);
UploadService.UploadClient client = new UploadService.UploadClient();
if (client.UpdateTest(dt))
{
MessageBox.Show("suceess");
}
else
{
MessageBox.Show("fail");
}
Here is my dataaccess class:
private static string connString;
private static SQLiteConnection conn;
public SQLiteDataAccess()
{
connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
private void OpenConn()
{
try
{
if (conn == null)
{
conn = new SQLiteConnection(connString);
}
if (conn.State != System.Data.ConnectionState.Open)
{
conn.Open();
}
}
catch (Exception ex)
{
LogUtil.Log("ex:" + ex.Message);
}
}
private void CloseConn()
{
try
{
if (conn.State != System.Data.ConnectionState.Closed)
{
conn.Close();
}
}
catch (Exception ex)
{
LogUtil.Log("ex:" + ex.Message);
}
}
public System.Data.DataTable GetDataTable(string sql)
{
DataTable dtResult = new DataTable();
try
{
OpenConn();
SQLiteDataAdapter adpter = new SQLiteDataAdapter(sql, conn);
DataSet ds = new DataSet();
adpter.Fill(ds);//here,I got the error.
if (ds.Tables.Count > 0)
{
dtResult = ds.Tables[0];
}
}
catch (Exception ex)
{
LogUtil.Log("ex:" + ex.Message);
}
finally
{
CloseConn();
}
return dtResult;
}
I got the error:
String was not recognized as a valid DateTime.
The database is SQLite, and table StockInTb contains some columns which type is datetime.
I've found some solutions like datetime.toString(s), but that's not what I need.
I don't know how to solve this odd problem. If somebody knows the answers, please tell me.
Thanks.
You can use parameter as below, Assume You have Column called MyDateTime and type is DateTime in your StockInTb Table then your query should be change as below.
Note that #InputDate going to add bay using Command.Parameters.Add method. Need to give the same name in both places and you can directly set parameter from DateTime object ( here it is named as InputDate
Command.CommandText = "select * from StockInTb where MyDateTime = #InputDate";
Command.Parameters.Add("#InputDate", InputDate);

can not select id more than 9 in table that is loaded from a xml file?

public class MessageManager
{
public const string FLDMessageID = "MessageID";
public const string FLDMessageText = "MessageText";
private string GetPath
{
get
{
return Environment.CurrentDirectory + #"\MessageList.xml";
}
}
private DataTable BuilDadataTable()
{
DataTable dtb = new DataTable("MessageList");
DataColumn clmn = new DataColumn("MessageID", typeof(System.Int32));
dtb.Columns.Add(clmn);
clmn = new DataColumn("MessageText", typeof(System.String));
dtb.Columns.Add(clmn);
return dtb;
}
public DataSet GetMessageStructure()
{
DataSet ds = new DataSet();
ds.Tables.Add(BuilDadataTable());
return ds;
}
public DataSet GetMessageListDS()
{
DataSet ds = null;
if (System.IO.File.Exists(GetPath))
{
ds = new DataSet();
ds.ReadXml(GetPath);
}
else
{
ds= GetMessageStructure();
}
return ds;
}
public void AddMessage(int MessageID, string MessageText)
{
DataSet ds = GetMessageListDS();
DataRow dr = ds.Tables[0].NewRow();
dr[FLDMessageID] = MessageID;
dr[FLDMessageText] = MessageText;
ds.Tables[0].Rows.Add(dr);
ds.WriteXml(this.GetPath);
}
public string GetMessage(int MessageID)
{
DataSet ds = GetMessageListDS();
string Result = "Invalid XML Error List";
if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count != 0)
{
DataRow[] drs = ds.Tables[0].Select("MessageID=" + MessageID.ToString()) ;
if (drs.Length > 0)
if(drs[0].ItemArray[1] !=DBNull.Value)
Result = drs[0].ItemArray[1].ToString();
}
return Result;
}
}
I have a xml file for manage message in my application.a class that called messageManager
is responsible of create xml file if not exists or read it into a table in application.
each entity in xml file have two element 1-MessageID 2-MessageText.
after add a meggage we can get a specified message by its id.
Problem:
Adding and getting message with id less than 10 dont have any problem
but when i add a message id with id mor than 9 getmessage() can not find it?
help please?
try to convert and compare as
DataRow[] drs = ds.Tables[0].Select("Convert(MessageID, 'System.String') = '"+MessageID.ToString()+"'");

Categories