I want to output values inside the class object to the console. Here's my code. This won't work. There is no error, but this won't output the values.
This is my method.
public ClsPayeDetails get_paydetail_byrow(int rowno)
{
string sql = "SELECT * FROM s07_01_payeDetails WHERE row_no='"+rowno+"'";
DataRow dr = LogIn.HR_Connection.GetSingleRow(sql);
ClsPayeDetails obj_det = null;
if (dr != null)
{
obj_det = new ClsPayeDetails(
decimal.Parse(dr["reducing_value"].ToString()),
dr["financial_year"].ToString(),
decimal.Parse(dr["lower_limit"].ToString()),
decimal.Parse(dr["upper_limit"].ToString()),
decimal.Parse(dr["percentage"].ToString())
);
}
Console.WriteLine(obj_det.ToString());
return obj_det;
}
// and this is where i call it. I think i'm doing this in incorrect way. //Any help would be appreciated.
private void testDetToolStripMenuItem_Click(object sender, EventArgs e)
{
cc_payroll.pyrl_cls_master.ClsPayeDetails dd = new cc_payroll.pyrl_cls_master.ClsPayeDetails();
dd.get_paydetail_byrow(1);
}
change your code
Console.WriteLine(obj_det.ToString());
to
Console.WriteLine(obj_det.getXXXXXXX().ToString());
getXXXXXXX() is your attribute in the class ClsPayeDetails.
ToString() function designed to return the value of 'single value object' like int, string... etc else it returns the object type.
So you need to:
Overwrite the function Tostring() in your class'ClsPayeDetails' to return a value not the type
Get object's properties and its values automatically.
you can use this code as it's or return any other string you want.
public override string ToString()
{
string result = "";
foreach (System.Reflection.PropertyInfo p in this.GetType().GetProperties())
{
if (!string.IsNullOrEmpty(result)) result += Environment.NewLine;
result += p.Name + ": " + p.GetValue(this);
}
return result;
}
You can use override string ToString function in your ClsPayeDetails class
public class ClsPayeDetails
{
//Your property class
public override string ToString()
{
System.Text.StringBuilder val = new System.Text.StringBuilder();
val.Append(string.Format("reducing_value = {0},", reducing_value));
val.Append(string.Format("financial_year = {0},", financial_year));
val.Append(string.Format("lower_limit = {0},", lower_limit));
val.Append(string.Format("upper_limit = {0},", upper_limit));
val.Append(string.Format("percentage = {0},", percentage));
return val.ToString();
}
}
This solved my problem. I changed my method go static and then accessed by class.
private void testDetToolStripMenuItem_Click(object sender, EventArgs e)
{
cc_payroll.pyrl_cls_master.ClsPayeDetails dd = ClsPayeDetails.get_paydetail_byrow(2);
Console.WriteLine(dd.FinancialYear.ToString());
Console.WriteLine(dd.lowerLimit.ToString());
Console.WriteLine(dd.upperLimit.ToString());
Console.WriteLine(dd.percenTage.ToString());
Console.WriteLine(dd.adjust.ToString());
}
and the method is
public static ClsPayeDetails get_paydetail_byrow(int rowno)
{
string sql = "SELECT * FROM s07_01_payeDetails WHERE row_no='" + rowno + "'";
DataRow dr = LogIn.HR_Connection.GetSingleRow(sql);
ClsPayeDetails obj_det = null;
if (dr != null)
{
obj_det = new ClsPayeDetails(
decimal.Parse(dr["reducing_value"].ToString()),
dr["financial_year"].ToString(),
decimal.Parse(dr["lower_limit"].ToString()),
decimal.Parse(dr["upper_limit"].ToString()),
decimal.Parse(dr["percentage"].ToString())
);
}
else
{
MessageBox.Show("This row does not exist !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return obj_det;
}
Related
i need to select specific two columns from a list and load those values for two combo boxes. i tried to do this using LINQ and it is passing me an error " Unable to cast object of type ' to type 'System.Collections.Generic.List ".
Here is my method,
private void getVehicleNo()
{
List<Exp_VehicleDTO> oData = oVehicleBL.VehiclesSearch(Convert.ToInt32(Session["CompanyID"].ToString()));
oData = ((List<Exp_VehicleDTO>)oData.SelectMany(x => x.VehicleNo)).ToList();
ddVehicleNo.DataSource = oData;
ddVehicleNo.DataBind();
}
here is the vehicle search method,
public List<Exp_VehicleDTO> VehiclesSearch(int companyId)
{
List<Exp_VehicleDTO> results = new List<Exp_VehicleDTO>();
try
{
using (CloudConnection oCloudConnection = new CloudConnection(DMSSWE.Common.ConnectionString))
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(" SELECT ");
sb.AppendLine("CompanyID,");
sb.AppendLine("VehicleId,");
sb.AppendLine("VehicleType,");
sb.AppendLine("VehicleNo,");
sb.AppendLine("Status,");
sb.AppendLine("CreatedDateTime,");
sb.AppendLine("CreatedBy,");
sb.AppendLine("CreatedMachine ");
sb.AppendLine(" FROM Exp_CompanyVehicle ");
sb.AppendLine(" WHERE 1=1 ");
sb.AppendLine(" AND (CompanyID=?CompanyID)");
oCloudConnection.CommandText = sb.ToString();
oCloudConnection.Parameters.Clear();
oCloudConnection.Parameters.Add(new Parameter { Name = "CompanyID", Value = companyId });
using (IDataReader dr = oCloudConnection.ExecuteReader())
{
while (dr.Read())
{
Exp_VehicleDTO result = new Exp_VehicleDTO();
result.CompanyId = Helper.GetDataValue<int>(dr, "CompanyID");
result.VehicleId = Helper.GetDataValue<int>(dr, "VehicleId");
result.VehicleType = Helper.GetDataValue<int>(dr, "VehicleType");
result.VehicleNo = Helper.GetDataValue<string>(dr, "VehicleNo");
result.Status = Helper.GetDataValue<int>(dr, "Status");
result.CreatedDateTime = Helper.GetDataValue<DateTime>(dr, "CreatedDateTime");
result.CreatedBy = Helper.GetDataValue<string>(dr, "CreatedBy");
result.CreatedMachine = Helper.GetDataValue<string>(dr, "CreatedMachine");
results.Add(result);
}
dr.Close();
}
}
return results;
}
catch (Exception ex)
{
Logger.Write(ex);
throw ex;
}
}
This line is the error :
((List<Exp_VehicleDTO>)oData.SelectMany(x => x.VehicleNo)).ToList()
oData.SelectMany(x => x.VehicleNo) returns IEnumerable<char> then you try to cast it to List<Exp_VehicleDTO>
Should be :
var vehicleNos = oData.Select(x => x.VehicleNo).ToList();
I think you need to use Select() not SelectMany(). Try changing your method to this:
private void getVehicleNo()
{
List<Exp_VehicleDTO> oData = oVehicleBL.VehiclesSearch(Convert.ToInt32(Session["CompanyID"].ToString()));
List<string> vehicleNoList = oData.Select(x => x.VehicleNo).ToList();
ddVehicleNo.DataSource = vehicleNoList;
ddVehicleNo.DataBind();
}
I wrote a GetLoan function:
private void GetLoan(RadioButton radiobutton)
{
if(radiobutton.Checked)
{
MessageBox.Show(radiobutton.Text);
}
}
and in order to get the necessary data from the radio button I did this,
bookCom = new SqlCommand("UPDATE d_Book SET ISBN = #isbn, Author = #author, Title = #title, Publisher = #publisher, Date = #date, Loan = #loan WHERE ISBN = #isbn ", bookCon);
String ISBN = textISBN.Text;
String Author = textAuthor.Text;
String Title = textTitle.Text;
String Publisher = textPublisher.Text;
String Date = textDate.Text;
GetLoan(rdbtn_Yes); // worked fine
GetLoan(rdbtn_No); // worked fine
bookCom.Connection = bookCon;
bookCon.Open();
if (bookCon.State == ConnectionState.Open)
{
bookCom.Parameters.AddWithValue("#isbn", ISBN);
bookCom.Parameters.AddWithValue("#author", Author);
bookCom.Parameters.AddWithValue("#title", Title);
bookCom.Parameters.AddWithValue("#publisher", Publisher);
bookCom.Parameters.AddWithValue("#date", Date);
bookCom.Parameters.Add("#loan", SqlDbType.Char).Value = GetLoan; // didn't work at all
}
Is there any way I could get GetLoan to work?
You have to specify the return type in the function:
private string GetLoan(RadioButton radiobutton)
{
if (radiobutton.Checked)
{
return "yes";
}
else
{
return "no";
}
}
Or as a bool in one line of code:
private bool GetLoan(RadioButton radiobutton)
{
return radiobutton.Checked;
}
And then you always need to pass RadioButton as a parameter. So change
bookCom.Parameters.Add("#loan", SqlDbType.Char).Value = GetLoan;
To
bookCom.Parameters.Add("#loan", SqlDbType.Char).Value = GetLoan(rdbtn_Yes);
But why not make it easier and just check which one is selected:
String Loan = "no";
if (rdbtn_Yes.Checked == true)
{
Loan = "yes";
}
bookCom.Parameters.Add("#loan", SqlDbType.Char).Value = Loan;
By reading the snippet provided, I understand that you need to ask user if he/she is interested in loan.
Instead of radio buttons for yes or no, you could consider using a check box then use the below function.
private string GetLoan(CheckBox chkBxGetLoan)
{
//returns string value as output.
return chkBxGetLoan.Checked ? "Y" : "N";
}
OR
private char GetLoan(CheckBox chkBxGetLoan)
{
//returns char value as output.
return chkBxGetLoan.Checked ? 'Y' : 'N';
}
I want to make a logger (in a library) that iterates through every field of whatever class and sets all values in a comma separated values line.
It's input value is a observable collection of whatever class. To make it generic I made it
ObservableCollection newObcObject.
public static bool WriteLog_Reflection(string fileName, long maxLogSizeMB, ObservableCollection<object>newObcObject, out string strError)
{
try
{
strError = string.Empty;
string lines = string.Empty;
foreach (var item in newObcObject)
{
foreach (var prop in item.GetType().GetProperties())
{
//string str = prop.Name + " = " + prop.GetValue(item, null).ToString();
lines += prop.GetValue(item, null).ToString() + "; ";
}
}
return true;
}
catch (Exception exc)
{
strError = exc.ToString();
return false;
}
}
and this works..
The problem now is how to convert a specific observable collection to an object observable collection.
This is my solution but I'm open to whatever other solutions.
thanx
You can cast IEnumerable using its Cast extension method.
Since ObservableCollection<> implements IEnumerable, this works for it too.
var c = new ObservableCollection<int>();
ObservableCollection<object> oc = c.Cast<int>();
Since all you do with newObcObject are enumeration and reflection, you don't need it to be ObservableCollection<T>. Just make it IEnumerable (you event don't need its generic counterpart):
public static bool WriteLog_Reflection(string fileName, long maxLogSizeMB,
IEnumerable newObcObject, out string strError)
{
// ...
}
But generic method with IEnumerable<T> will allow to simplify code:
public static bool WriteLog_Reflection<T>(string fileName, long maxLogSizeMB,
IEnumerable<T> newObcObject, out string strError)
{
// ...
// This:
//
// string lines = string.Empty;
// foreach (var item in newObcObject)
// {
// foreach (var prop in item.GetType().GetProperties())
// {
// lines += prop.GetValue(item, null).ToString() + "; ";
// }
// }
//
// could be replaced to this:
var lines = string.Join("; ", newObcObject
.SelectMany(item => item.GetType().GetProperties(),
(item, property) => property.GetValue(item, null)));
// ...
}
You don't need to pass ObservableCollection, since you use reflection IEnumerable is enough. Almost all collections implement IEnumerable (the non generic one!):
public static bool WriteLog_Reflection(string fileName, long maxLogSizeMB, IEnumerable newObcObject, out string strError)
{
try
{
strError = string.Empty;
string lines = string.Empty;
foreach (var item in newObcObject)
{
foreach (var prop in item.GetType().GetProperties())
{
//string str = prop.Name + " = " + prop.GetValue(item, null).ToString();
lines += prop.GetValue(item, null).ToString() + "; ";
}
}
return true;
}
catch (Exception exc)
{
strError = exc.ToString();
return false;
}
}
I'm trying to access a certain variable from another class, however I'm not able to do so. I have two buttons - the first button sets token to an html template file. The second should generate the file. The first button calls the class. The second button should call the string from the class for generation.
My first button is as follows:
private void btnTemplate_Click(object sender, EventArgs e)
{
if ((txtTitle.Text == "") && (txtSku.Text == "") && (txtPrice.Text == "") && (txtDesc.Text == "") && (txtImg.Text == ""))
{
MessageBox.Show("No row selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
OpenFileDialog SetData = new OpenFileDialog();
SetData.Filter = "HTML|*.html;";
GlobalVar.setPath = "C:\\genHtml.html";
var result = SetData.ShowDialog();
DataSet ds = new DataSet();
if (result == DialogResult.OK)
{
string fileName = SetData.FileName;
var template = new HtmlTemplate(#SetData.FileName);
var output = template.Render(new
{
TITLE = txtTitle.Text,
SKU = txtSku.Text,
PRICE = txtPrice.Text,
DESC = txtDesc.Text,
IMAGE = txtImg.Text
});
File.WriteAllText(#GlobalVar.setPath, output);
}
}
}
My second button:
private void btnGenerate_Click(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process.Start(GlobalVar.setPath);
}
catch
{
MessageBox.Show("Please select a template first", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I get an error with the string output. How can I call string 'output' for the second button?
My class is as follows:
class HtmlTemplate
{
private string _html;
public HtmlTemplate(string templatePath)
{
using (var reader = new StreamReader(templatePath))
_html = reader.ReadToEnd();
}
public string Render(object values)
{
string output = _html;
foreach (var p in values.GetType().GetProperties())
output = output.Replace("[" + p.Name + "]", (p.GetValue(values, null) as string) ?? string.Empty);
return output;
}
}
There is not enough context to be sure, but in the case of the second button it looks like output is not declared as a variable or possibly not assigned a (correct) value.
File.WriteAllText(#GlobalVar.setPath, output);
could become
var template = new HtmlTemplate(#SetData.FileName);
File.WriteAllText(#GlobalVar.setPath, template.Render(new
{
TITLE = txtTitle.Text,
SKU = txtSku.Text,
PRICE = txtPrice.Text,
DESC = txtDesc.Text,
IMAGE = txtImg.Text
});
or alternatively
var template = new HtmlTemplate(#SetData.FileName);
var output = template.Render(new
{
TITLE = txtTitle.Text,
SKU = txtSku.Text,
PRICE = txtPrice.Text,
DESC = txtDesc.Text,
IMAGE = txtImg.Text
});
File.WriteAllText(#GlobalVar.setPath, output);
dropdownlist selected value is not changing. although the string _month also contain the value but dropdownlist is not getting it.all other are working fine but only ddlMonth.selected value is not changing.i have assigned _month value to it but its not changing why? only ddlMonth is not changing all other are working fine why ddlmonth is not changing?
if (_objMonth.Contains("Month"))
{
string _Month = (string)_objMonth.GetData("Month");
ddlMonth.SelectedValue = _Month;
///here ddlMonth.selected value is not getting new value from _month
}
Other code is below
protected void Page_Load(object sender, System.EventArgs e)
{
if (Page.IsPostBack)
return;
try
{
OnLoad();
GetYears();
if (!string.IsNullOrEmpty(ddlYear.SelectedValue))
hYearId.Value = ddlYear.SelectedValue;
GetPeriods(Convert.ToInt32(hYearId.Value));
GetDepartment();
GetSection();
#region Get Selected login user department and section
ddldepartment.SelectedValue = CommonMethods.UserContext.EmployeeDeparmentID;
ddlSection.SelectedValue = CommonMethods.UserContext.EmployeeSectionID;
#endregion
ddldepartment_SelectedIndexChanged(null, null);
ddlemp_SelectedIndexChanged(null, null);
string name = Request.QueryString["id"] as string;
#region Create Cache object
ICacheManager _objYear = CacheFactory.GetCacheManager();//Create cache object
ICacheManager _objMonth = CacheFactory.GetCacheManager();//Create cache object
ICacheManager _objDepartment = CacheFactory.GetCacheManager();//Create cache object
ICacheManager _objSection = CacheFactory.GetCacheManager();//Create cache object
#endregion
if (Request.QueryString["ClickTag"]!=null)
{
#region set Cached items
if (Request.QueryString["ClickTag"].ToString() == "1")
{
if (_objYear.Contains("Year"))
{
string _Year = (string)_objYear.GetData("Year");
ddlYear.SelectedValue = _Year;
}
if (_objMonth.Contains("Month"))
{
string _Month = (string)_objMonth.GetData("Month");
ddlMonth.SelectedValue= _Month;
}
if (_objDepartment.Contains("Department"))
{
string _Department = (string)_objDepartment.GetData("Department");
ddldepartment.SelectedValue= _Department;
}
if (_objSection.Contains("Section"))
{
string _Section = (string)_objSection.GetData("Section");
ddlSection.SelectedValue = _Section;
}
}
#endregion
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(ddlMonth.SelectedValue))
{
hClpid.Value = ddlMonth.SelectedValue.Split(',')[0];
Session["Startdate"] = ddlMonth.SelectedValue.Split(',')[2];
Session["EndDate"] = ddlMonth.SelectedValue.Split(',')[3];
ddldepartment_SelectedIndexChanged(null, null);
ddlemp_SelectedIndexChanged(null, null);
if (ddlSection.SelectedIndex > 0)
ddlSection_SelectedIndexChanged(null, null);
}
}
void GetPeriods(int _year)
{
IBLCalenderPeriod _bl = (IBLCalenderPeriod)SetupBLFactory.GetCalenderPeriod();
DataSet _ds = (DataSet)_bl.GetPeriodIdsByYear(_year).GetMaster();
_ds.Tables[0].Columns.Add("ID");
foreach (DataRow _dr in _ds.Tables[0].Rows)
{
_dr["ID"] = _dr["CLP_ID"] + "," + _dr["clp_activeperiod"] + "," + _dr["CLP_DATESTART"] + "," + _dr["CLP_DATEEND"] + "";
}
ddlMonth.DataSource = _ds.Tables[0];
ddlMonth.DataTextField = "CLP_DESCRIPTION";
ddlMonth.DataValueField = "ID";
ddlMonth.DataBind();
foreach (DataRow _dr in _ds.Tables[0].Rows)
{
if (_dr["clp_activeperiod"] != null)
if (_dr["clp_activeperiod"].ToString() == "1")
{
ddlMonth.SelectedValue = _dr["ID"].ToString();
hClpid.Value = ddlMonth.SelectedValue.Split(',')[0];
Session["Startdate"] = ddlMonth.SelectedValue.Split(',')[2];
Session["EndDate"] = ddlMonth.SelectedValue.Split(',')[3];
break;
}
else
{
ddlMonth.SelectedIndex = 0;
hClpid.Value = "0";
}
}
}
I think you are setting a value in ddlMonth but ddlMonth do not have that binded value.. Try to bind list of values in your ddlMonth before setting a value to it
Please next time format the code before posting.
For the problem I think the solution is to put the region where you set the SelectedValue inside an
if(!isPostback){...}
I suggest you to take a look to the documentation about page lifecycle, because the explanation is that the Page_Load in executed not only the first time you load a page, but also for every postback (if you don't use the if(!isPostback){...}