I currently have a class to retrieve records from a sql database and put them into a list.
The record have multiple columns and i need to insert the data from the second column from all records into a combobox.
How is this achieved as im unable to find anything about it.
Processor Class:
namespace RegForm
{
public class ClientProcessor
{
public List<Client> ClientList = new List<Client>();
public ClientProcessor()
{
}
public void LoadClients()
{
string sqlc = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
SqlConnection conn = new SqlConnection(sqlc);
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
SqlCommand cmd = new SqlCommand("SELECT * FROM Clients ORDER BY CID", conn);
try
{
SqlDataReader dr = cmd.ExecuteReader();
ClientList = new List<Client>();
if (dr.HasRows)
{
while (dr.Read())
{
Client newClient = new Client();
newClient.ID = Convert.ToInt32(dr["CID"]);
newClient.CNAME= dr["CNAME"].ToString();
ClientList.Add(newClient);
}
}
}
catch (Exception EX)
{
Console.WriteLine(EX.Message);
Console.WriteLine(EX.InnerException);
}
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}
Assuming your data in DataTable, you can do something like:
DataTable dt;
List <T> lst = new List<T>(); //replace T with your column type
foreach (DataRow r in dt.Rows)
{
lst.Add(r[1]); //insert to list
combobox.Iteam.add(r[1]); //insert to combox
}
You can try this
class MyData
{
public string Id{get;set;}
public string Name{get;set;}
//Other properties
}
Inside bind function
public void BindData(List<MyData> list)
{
//Assuming list is not null
var dataFromSecondColumn = list.Select(l=>l.Name).ToList();
//Reset of your code.
comboBox1.DataSource = dataFromSecondColumn;
}
Related
I want to select an item from a combobox and it should show the item that has been selected.
When I use:
cmd.Parameters.AddWithValue("#ItemCateg", categCB.SelectedIndex);
it will only show the number of the item
if I use
cmd.Parameters.AddWithValue("#ItemCateg", categCB.SelectedItem);
or
cmd.Parameters.AddWithValue("#ItemCateg", categCB.SelectedItem.ToString());
It will only print a message like "System.Data.DataRowView"
Here's the whole Code:
private void GetCategory()
{
Con.Open();
SqlCommand cmd = new SqlCommand("Select * from CategoryTBL", Con);
SqlDataReader Rdr;
Rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("CategoryName", typeof(String));
dt.Load(Rdr);
categCB.ValueMember = "CategoryName";
categCB.DataSource = dt;
Con.Close();
}
private void addbtn_Click(object sender, EventArgs e)
{
if (itemIDtxt.Text == "" || itemnametxt.Text == "" || descriptiontxt.Text == "" || manufacturertxt.Text == "" || amounttxt.Text == "" || quantitytxt.Text == "")
{
MessageBox.Show("Missing Data");
}
else
{
int tAmount = Convert.ToInt32(amounttxt.Text) * Convert.ToInt32(quantitytxt.Text);
try
{
Con.Open();
SqlCommand cmd = new SqlCommand("insert into ItemDetailTBL values(#iID, #ItemNa, #ItemCateg, #ItemDesc, #ItemMan, #ItemAmoun, #ItemQua, #ItemExDate, #ItemtAmount)", Con);
cmd.CommandType = CommandType.Text;
Int32.Parse(itemIDtxt.Text);
cmd.Parameters.AddWithValue("#iID", itemIDtxt.Text);
cmd.Parameters.AddWithValue("#ItemNa", itemnametxt.Text);
cmd.Parameters.AddWithValue("#ItemCateg", categCB.SelectedIndex);
cmd.Parameters.AddWithValue("#ItemDesc", descriptiontxt.Text.ToString());
cmd.Parameters.AddWithValue("#ItemMan", manufacturertxt.Text);
cmd.Parameters.AddWithValue("#ItemAmoun", amounttxt.Text);
cmd.Parameters.AddWithValue("#ItemQua", quantitytxt.Text);
cmd.Parameters.AddWithValue("#ItemExDate", expdatepick.Text);
cmd.Parameters.AddWithValue("#ItemtAmount", tAmount);
cmd.ExecuteNonQuery();
MessageBox.Show("New Data Has been Added to the Inventory");
Con.Close();
Showitem();
addHis();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
Here is a pattern to following. Create a class representing the category table and override ToString with what should be shown in the ComboBox.
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public override string ToString() => CategoryName;
}
Rewrite you code to read data to this pattern
public static List<Category> Categories()
{
List<Category> list = new List<Category>() ;
using var cn = new SqlConnection(ConnectionString);
using var cmd = new SqlCommand { Connection = cn,
CommandText = "SELECT CategoryID ,CategoryName FROM dbo.Categories" };
cn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
list.Add(new Category() { CategoryID = reader.GetInt32(0), CategoryName = reader.GetString(1) });
}
return list;
}
The method above for this example resides in a class named SqlServerOperations.
Form code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
categCB.DataSource = SqlServerOperations.Categories();
}
private void GetCurrentCategoryButton_Click(object sender, EventArgs e)
{
var current = (Category)categCB.SelectedItem;
MessageBox.Show($"{current.CategoryID,-5}{current.CategoryName}");
}
}
/*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.
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:
I have problem with null values, I want to insert from sql table nulls ( from datetime column) into datagridview, and datagridview return error.
Communication Exception was unhandled by user code
Code:
public class Pismo
{
public int Id { get; set; }
public string PW { get; set; }
public DateTime? Data_Wysylki { get; set; }
}
public ObservableCollection<Pismo> ReadPisma(int id_pismo)
{
ObservableCollection<Pismo> result = new ObservableCollection<Pismo>();
string nwConn = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlDataReader dr;
SqlConnection conn = new SqlConnection(nwConn);
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.CommandText = "INSERT";
cmd.Parameters.AddWithValue("#id", id);
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
Pismo wiersz = new Pismo();
wi.Id = dr.GetInt32(0);
wi.PW = dr.GetString(1);
wi.Data_Wysylki = dr.GetDateTime(2);
result.Add(wi);
}
dr.Close();
return result;
}
catch (SqlException e)
{
Pismo wi = new Pismo();
wi.Id = e.Message;
result.Add(wi);
return result;
}
finally
{
conn.Close();
};
}
<sdk:DataGridTextColumn Header="Data WysyĆki" Binding="{Binding Data_Wysylki, StringFormat='yyyy/MM/dd'}"/>
I try to add this below
if (wi.Data_Wysylki.HasValue) wi.Data_Wysylki = dr.GetDateTime(16);
after that error didnt show but in datagridview all column (even with some dates) was null
I have a class
public class UserInfo
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
And I need to make a link between the database, with this code:
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.HasRows)
{
}
}
Using Reflection on all the lines of the database.
And store them into a generic List:
List<UserInfo> users = new List<UserInfo>();
I GOT IT !!
I GOT IT !!
This is the result, maybe someone needs it !!
public List<UserInfo> GetAllUsers()
{
List<UserInfo> users = new List<UserInfo>();
try
{
using (SqlConnection sqlConnection = connectionString)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "dbo.GetAllUsers";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection;
sqlConnection.Open();
using (SqlDataReader dataReader = cmd.ExecuteReader())
{
if (dataReader.HasRows)
{
while (dataReader.Read())
{
UserInfo user = new UserInfo();
PropertyInfo[] pList = typeof(UserInfo).GetProperties();
foreach (PropertyInfo pi in pList)
{
object value = dataReader[pi.Name];
if (!value.GetType().Equals(typeof(DBNull)))
{
users.GetType().GetProperty(pi.Name, BindingFlags.Public | BindingFlags.Instance).SetValue(user, value, null);
}
}
users.Add(user);
}
}
else
{
users = null;
}
}
}
sqlConnection.Close();
}
}
catch (Exception)
{
return null;
}
return users;
}