Binding dropdownlist with generic list in 3-tier architecture - c#

/*data access layer */
public DataSet getdata(string procedurename, SqlParameter[] param)
{
try
{
SqlCommand command;
command = new SqlCommand(procedurename, connection);
command.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet set = new DataSet();
if (param != null)
{
for (int i = 0; i < param.Length; i++)
{
command.Parameters.Add(param[i]);
}
}
adapter.Fill(set);
return set;
}
catch (Exception ex)
{
throw ex;
}
finally
{
closeConnection();
}
}
Middle Tier:
public class dropdownbind
{
private string _itemName;
private int _itemvalue;
public int Itemvalue
{
get { return _itemvalue; }
set { _itemvalue = value; }
}
public string ItemName
{
get { return _itemName; }
set { _itemName = value; }
}
public List<dropdownbind> getDepartment()
{
DBlist obj = new DBlist();
DataSet ds = obj.getdata("str_getdepartment",null);
List<dropdownbind> departments = new List<dropdownbind>();
foreach (DataRow orow in ds.Tables[0].Rows)
{
dropdownbind dlist = new dropdownbind();
dlist.ItemName = orow["deparment_name"].ToString();
dlist.Itemvalue = int.Parse(orow["id"].ToString());
departments.Add(dlist);
}
return departments;
}
}
UI:-
protected void BindDdlList()
{
dropdownbind dlist = new dropdownbind();
List<dropdownbind> departments = dlist.getDepartment();
ddlEmpDepatment.DataSource = departments;
ddlEmpDepatment.DataTextField = dlist.ItemName;
ddlEmpDepatment.DataValueField = dlist.Itemvalue.ToString();
ddlEmpDepatment.DataBind();
}
i am trying to bind departments to dropdownlist using 3-tier architecture.
but this code is not working, it shows middletier.dropdownbind in text field.

You need to correct the DataTextField & DataValueField properties like this:-
ddlEmpDepatment.DataValueField = "Itemvalue";
ddlEmpDepatment.DataTextField = "ItemName";
You are specifying the property name rather you need to specify the property name as string.

Related

Using List of <struct> as a datasource to a listview shows object.tostring() instead of DisplayMember

With a list of struct as the Datasource for a Listbox, I am getting the Object.ToString() rather than the expected field value from the struct
This was working OK when I assigned a DataTable as the DataSource after setting the DisplayMember.
However, I wanted to try using a list of struct (int ID, String Name) instead and despite having set DisplayMember to "Name" before assigning the Datasource to the List I get the row object.toString().
Any help would be fantastic.
On Form Load:
private void frmTestProof_Load(object sender, EventArgs e)
{
TestMaker tm = new TestMaker();
tm.LoadMakersToListbox(ref lstboxMaker);
}
class TestMaker
{
public struct MakerRecord
{
public int MakerID;
public String MakerName;
public MakerRecord(int ID, String Name)
{
MakerID = ID;
MakerName = Name;
}
}
public SQLiteConnection DBconn;
public String thisPath = "";
public SQLiteCommand sqlCommand = new SQLiteCommand();
public DataSet dsMaker = new DataSet();
public SQLiteDataAdapter daMaker = new SQLiteDataAdapter();
public TestMaker()
{
thisPath = "c:\\sqlite\\abc.db";
DBconn = new SQLiteConnection(String.Format("Data Source={0};Version=3;", thisPath));
DBconn.Open();
sqlCommand.Connection = DBconn;
sqlCommand.CommandType = CommandType.Text;
}
public List<MakerRecord> GetListOfMakers()
{
List<MakerRecord> makerList = new List<MakerRecord>();
String sqlMaker = "SELECT ID, VehicleMakerName FROM VehicleMakers WHERE VehicleMakerName IS NOT NULL"
;
sqlCommand.CommandText = sqlMaker;
daMaker.SelectCommand = sqlCommand;
try
{
daMaker.Fill(dsMaker, "Makers");
makerList = (from item in dsMaker.Tables["Makers"].AsEnumerable()
select new MakerRecord()
{
MakerID = Convert.ToInt32(item["ID"]),
MakerName = item["VehicleMakerName"].ToString()
}).ToList();
}
catch (Exception ex)
{
MessageBox.Show(String.Format("List of Makers - Error ({0})", ex.Message));
}
return makerList;
}
public void LoadMakersToListbox(ref ListBox lb)
{
lb.Items.Clear();
lb.ValueMember = "MakerID";
lb.DisplayMember = "MakerName";
lb.DataSource = GetListOfMakers();
}
}
Change public String MakerName; to public string MakerName {get;set;} and public int MakerID; to public int MakerID {get;set;}

Make a dynamic sqlite table creating and inserting function

I have around 8-9 functions for filling tables from SQL to Sqlite and I am trying to make a dynamic function on which I will just pass some params and it will create the sqlite table (if it doesn't exist), create multiple instances in a loop of the type I want to insert in the specific table, set the properties for it and then insert it. Here are example functions:
private bool ReloadItemsFromServer()
{
try
{
using (GS.cnn)
{
SqlCommand command = new SqlCommand("rsp_FillItem_MobileDevice;", GS.cnn);
command.CommandType = System.Data.CommandType.StoredProcedure;
GS.cnn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "DataBase.PremierAndroid");
using (var sqliteConn = new SQLiteConnection(dbPath))
{
sqliteConn.CreateTable<Item>();
while (reader.Read())
{
{
var newItem = new Item();
newItem.ItemID = reader.GetInt32(0);
newItem.ItemBaseID = reader.GetInt32(1);
newItem.BrandID = reader.GetInt32(2);
newItem.Issue = reader.GetInt32(3);
sqliteConn.Insert(newItem);
}
}
}
}
else
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(Resources.GetString(Resource.String.NoRowsForItemFound));
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
reader.Close();
}
return true;
}
catch (Exception ex)
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(ex.Message);
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
finally
{
if (GS.cnn.State != ConnectionState.Closed)
{
GS.cnn.Close();
}
}
}
and here's another one:
private bool ReloadContragentsFromServer()
{
try
{
using (GS.cnn)
{
SqlCommand command = new SqlCommand("rsp_FillContragent_MobileDevice;", GS.cnn);
command.CommandType = System.Data.CommandType.StoredProcedure;
GS.cnn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "DataBase.PremierAndroid");
using (var sqliteConn = new SQLiteConnection(dbPath))
{
sqliteConn.CreateTable<Contragent>();
while (reader.Read())
{
{
var newContragent = new Contragent();
newContragent.ContragentID = reader.GetInt32(0);
newContragent.ContragentTypeID = reader.GetInt32(1);
newContragent.ContragentGroupID = reader.GetInt32(2);
newContragent.FullName = reader.GetString(3);
newContragent.BULSTAT = reader.GetString(4);
newContragent.ItemPriceGroupID = reader.GetInt32(5);
newContragent.ItemDiscountGroupID = reader.GetInt32(6);
sqliteConn.Insert(newContragent);
}
}
}
}
else
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(Resources.GetString(Resource.String.NoRowsForContragentFound));
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
reader.Close();
}
return true;
}
catch (Exception ex)
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(ex.Message);
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
finally
{
if (GS.cnn.State != ConnectionState.Closed)
{
GS.cnn.Close();
}
}
}
You can see what's different. How can I make it so I just call one method and give it some params so i dont have 8-9 blocks of code which are somewhat repeating?
I currently have this as a dynamic function (unfinished):
private bool LoadDataFromServer(string procedure, Type passedType)
{
try
{
using (GS.cnn)
{
SqlCommand command = new SqlCommand(procedure, GS.cnn);
command.CommandType = System.Data.CommandType.StoredProcedure;
GS.cnn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "DataBase.PremierAndroid");
using (var sqliteConn = new SQLiteConnection(dbPath))
{
sqliteConn.CreateTable(passedType);
while (reader.Read()) //to do > i++ bla bla
{
{
var newItem = Activator.CreateInstance(passedType);
//newItem - loop through properties and set = reader.get(int/string)(i)
sqliteConn.Insert(newItem);
}
}
}
}
else
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(Resources.GetString(Resource.String.NoRowsForItemFound));
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
reader.Close();
}
return true;
}
catch (Exception ex)
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(ex.Message);
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
finally
{
if (GS.cnn.State != ConnectionState.Closed)
{
GS.cnn.Close();
}
}
}
Thank you
let reflection and inherit help like this:
class Caller{
// see how it sends objects to method 'processAllClasses' with different classes
void main(){
ItemClass1 i1 = new ItemClass1();
i1.setItemsB(1,2);
processAllClasses(i1);
ItemClass2 i2 = new ItemClass2();
i2.setItemsB(10, 20);
processAllClasses(i2);
}
//using reflection and inherit to process different classes, obj is what need to be processed on.
//alternative way:
//get members from the type, then assign values to them one by one
void processAllClasses(ParentClass myobjvalue)
{
Type realtype = myobjvalue.GetType();
ParentClass myobj = new ParentClass();
MethodInfo mi = realtype.GetMethod("setItemsA");
object obj = Activator.CreateInstance(realtype);
Object[] parameter = new Object[] { myobjvalue };
mi.Invoke(obj, parameter);
}
}
class ParentClass {
}
class ItemClass1: ParentClass
{
int ItemID;
int ItemBaseID;
public void setItemsA(ItemClass1 itemclass1)
{
this.ItemID = itemclass1.ItemID;
this.ItemBaseID = itemclass1.ItemBaseID;
}
public void setItemsB(int ItemID, int ItemBaseID)
{
this.ItemID = ItemID;
this.ItemBaseID = ItemBaseID;
}
}
class ItemClass2 : ParentClass
{
int ContragentID;
int ContragentTypeID;
public void setItemsA(ItemClass2 itemclass2)
{
this.ContragentID = itemclass2.ContragentID;
this.ContragentTypeID = itemclass2.ContragentTypeID;
}
public void setItemsB(int ContragentID, int ContragentTypeID)
{
this.ContragentID = ContragentID;
this.ContragentTypeID = ContragentTypeID;
}
}

How To Identify button click of a node in dataTreeListView1 in C#

I have dataTreeListView named dataTreeListView1 i wish to get the name of the node which i clicked can any one please help me to do this
in the above picture if i click yes i wish to get yes on messagebox
what i tried to do is
private void dataTreeListView1_AfterSelect(object sender, EventArgs e)
{
MessageBox.Show("hello");
}
and the node are loaded dynamically means they are from database.
List<Class3> list = new List<Class3>();
list = Class3.GetList(startDate, endDate, con);
this.dataTreeListView1.ParentKeyAspectName = "ParentId";
this.dataTreeListView1.RootKeyValueString = "NUll";
BrightIdeasSoftware.OLVColumn col = new BrightIdeasSoftware.OLVColumn();
col.Width = 10;
dataTreeListView1.DataSource = list;
foreach (ColumnHeader column in this.dataTreeListView1.Columns)
{
column.Width = 140 + 140 + this.dataTreeListView1.SmallImageSize.Width;
}
this.dataTreeListView1.Columns.RemoveByKey("Id");
this.dataTreeListView1.Columns.RemoveByKey("ParentId");
this is how i show data in datatreelist view
public Class3()
{
this.xName = "";
this.xId = "";
this.xParentId = "";
this.xcredit = 0.0M;
this.xdebit = 0.0M;
this.xx = 0.0M;
this.xy = 0.0M;
}
public String Ledger
{
get { return this.xName; }
set { this.xName = value; }
}
public String Id
{
get { return this.xId; }
set { this.xId = value; }
}
public String ParentId
{
get { return this.xParentId; }
set { this.xParentId = value; }
}
public Decimal Credit
{
get { return this.xcredit; }
set { this.xcredit = value; }
}
public Decimal Debit
{
get { return this.xdebit; }
set { this.xdebit = value; }
}
public decimal x
{
get { return this.xx; }
set { this.xx = value; }
}
public decimal y
{
get { return this.xy; }
set { this.xy = value; }
}
public static List<Class3> GetList(DateTime startDate, DateTime endDate, SqlConnection con)
{
List<Class3> oList = new List<Class3>();
Buisiness b = new Buisiness();
try
{
decimal totalcredit = 0;
decimal totaldebit = 0;
con.Open();
// // Make sql readable
DataTable dt = new DataTable();
string sql = #"Select Ledger.LedId,Ledger.LedName,Ledger.MasterLedger from Ledger where Ledger.Date >= #prmStartDate and Ledger.Date <= #prmEndDate group by Ledger.MasterLedger,Ledger.LedId,Ledger.LedName";
// wrap IDisposable (SqlCommand) into using
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#prmStartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#prmEndDate", SqlDbType.DateTime).Value = endDate;
SqlDataReader da = cmd.ExecuteReader();
while (da.Read())
{
Class3 oClass = new Class3();
oClass.Ledger = da["LedName"].ToString();
oClass.Id = da["LedId"].ToString();
oClass.ParentId = da["MasterLedger"].ToString();
Dictionary<string, decimal> d = b.findclosingbalanceofledger(da["LedId"].ToString());
/* if (da["MasterLedger"].ToString() == "NUll")
{
oClass.Debit = findsumofallchilds(da["LedId"].ToString(), con, startDate, endDate);
}
else
{*/
if (d.FirstOrDefault().Key == "debit")
{
d.FirstOrDefault().Value.ToString();
d.FirstOrDefault().Value.ToString();
totaldebit = totaldebit + d.FirstOrDefault().Value;
oClass.Debit = d.FirstOrDefault().Value;
}
else if (d.FirstOrDefault().Key == "credit")
{
d.FirstOrDefault().Value.ToString();
totalcredit = totalcredit + d.FirstOrDefault().Value;
oClass.Credit = d.FirstOrDefault().Value;
}
/* }*/
oList.Add(oClass);
}
}
con.Close();
}
catch (Exception exe)
{
MessageBox.Show(exe.Message);
}
finally
{
con.Close();
}
return oList;
}
i have changed my code this
private void dataTreeListView1_AfterSelect(object sender, EventArgs e)
{
MessageBox.Show("hello");
}
to
private void dataTreeListView1_CellClick(object sender, CellClickEventArgs e)
{
MessageBox.Show("helo");
}
but no change

Using ADO.Net Core With Models, I want to Display Data From Different Relational Tables But It Gives Me Some Errors

I have an error in the code below. When I use it for one table it works fine, But it doesn't work for relational tables.
Method for displaying all records:
public List<AdminUserRegisterModel> GetAll()
{
List<AdminUserRegisterModel> List = new List<AdminUserRegisterModel>();
try
{
SqlCommand cmd = new SqlCommand("sp_admin_user_search_all", connection);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr;
connection.Open();
dr = cmd.ExecuteReader();
// while(dr.HasRows)
//{
while(dr.Read())
{
AdminUserRegisterModel obj = new AdminUserRegisterModel();
obj.adminUsers.adminId = Convert.ToInt32(dr["adminId"]);
obj.adminUsers.adminName = Convert.ToString(dr["adminName"]);
obj.adminUsers.adminEmail = Convert.ToString(dr["adminEmail"]);
obj.adminUsers.adminPassword = Convert.ToString(dr["adminPassword"]);
obj.adminUsers.adminStatus = Convert.ToInt32(dr["adminStatus"]);
obj.adminUsers.joinDate = Convert.ToDateTime(dr["adminJoinDate"]);
// AdminUserProfile table
obj.adminProfiles.adminProfileId = Convert.ToInt32(dr["profileId"]);
obj.adminProfiles.firstName = Convert.ToString(dr["firstName"]);
obj.adminProfiles.lastName = Convert.ToString(dr["lastName"]);
obj.adminProfiles.cnic = Convert.ToString(dr["cnic"]);
obj.adminProfiles.profileImg = Convert.ToString(dr["profileImg"]);
obj.adminProfiles.adminId = Convert.ToInt32(dr["adminId"]);
List.Add(obj);
}
//}
if (!dr.IsClosed)
{
dr.Close();
}
connection.Close();
return List;
}
catch
{
connection.Close();
return null;
}
finally
{
connection.Close();
}
}
Controller method:
// Display All Records
public ActionResult Display()
{
repObj = new AdminUserRegisterRepository();
return View(repObj.GetAll());
}
Model class:
public class AdminUserRegisterModel
{
public adminUser adminUsers { get; set; }
public admin_profile adminProfiles { get; set; }
}
It gives me the following error:

Object Data Source function returning only 1 value

I am using ObjectDataSource for my Gridview.
The function I am using to return values is just returning a single value that is the last one from the table.
What changes do I make to return all the values.
public class Employees
{
public int e_number;
public string e_name;
public string e_designation;
private SqlConnection conn = null;
private SqlCommand cmd = null;
private string constring = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
public Employees()
{
conn = new SqlConnection(constring);
cmd = new SqlCommand();
}
public int Employee
{
get
{
return e_number;
}
set
{
e_number = value;
}
}
public string Name
{
get
{
return e_name;
}
set
{
e_name = value;
}
}
public string Designation
{
get
{
return e_designation;
}
set
{
e_designation = value;
}
}
public Employees GetEmployee()
{
string strquery = "select [Number],[Name],[Designation] from [Users]";
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strquery;
SqlDataReader objSqlDataReader = cmd.ExecuteReader();
int counter = 0;
// ArrayList myObj = new ArrayList();
// Employees objEmployees = new Employees();
Employees emp = null;
//if (objSqlDataReader.Read())
while(objSqlDataReader.Read())
{
emp = new Employees();
// myObj[counter] = new Employees();
// Employees employee = new Employees();
emp.Employee = (int)objSqlDataReader["Number"];
emp.Name=(string)objSqlDataReader["Name"];
emp.Designation = (string)objSqlDataReader["Designation"];
// objEmployees.e_number = (int)objSqlDataReader["Number"];
// objEmployees.e_name = (string)objSqlDataReader["Name"];
//objEmployees.e_designation = (string)objSqlDataReader["Designation"];
}
conn.Close();
return emp;
//return objEmployees;
}
}
}
I have tried all approaches like making array of objects but I am not able to .
Please could you tell me what to add in my code.
You need to return a list of employees. You are only returning a single one, the last instance after you exit the loop:
public List<Employees> GetEmployees()
{
..
List<Employees> emps = new List<Employees>();
Employees emp = null;
while (..)
{
emp = new Employees();
..
emps.Add(emp);
}
return emps;
}

Categories