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}");
}
}
Related
For example I want to display the logged in user's information from database to another form like firstname and lastname I got no problem in admin because it only has one form or details for it. I tried passing the text in textbox username to another form and then select the passed text to display the other information of it but it won't, here's my code btw.
private void button2_Click(object sender, EventArgs e)
{
int i = 0;
MySqlCommand comm = con.CreateCommand();
comm.CommandText = "select * from accountinfo where username = #user and pass = #password";
comm.Parameters.AddWithValue("#user", textBox1.Text);
comm.Parameters.AddWithValue("#password", textBox2.Text);
MySqlDataReader myReader;
con.Open();
comm.ExecuteNonQuery();
myReader = comm.ExecuteReader();
string accountType = string.Empty;
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(comm);
i = Convert.ToInt32(dt.Rows.Count.ToString());
while (myReader.Read())
{
i = i + 1;
accountType = myReader["accountType"].ToString();
}
if (i == 0)
{
MessageBox.Show("Wrong username or password!");
}
else if (accountType == "admin")
{
MessageBox.Show("Welcome admin");
this.Hide();
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
Form3 frm3 = new Form3();
frm3.Show();
}
else
{
MessageBox.Show("Welcome");
this.Hide();
using(var frm4 = new Form4())
{
frm4.FirstName = textBox1.Text;
frm4.ShowDialog();
}
}
con.Close();
}
and my code in second form
public partial class Form4 : Form
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string CellNo { get; set; }
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
tbUser.Text = FirstName;
try
{
string MyConnection2 = "server=localhost;user id=root;database=account;persistsecurityinfo=True;PASSWORD=test123;SslMode=none";
string Query = "SELECT firstname = '" + tbFN.Text + "' from accountinfo WHERE username = '" + tbUser + "' " ;
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Logged in user information is kind of static for all your application, so you should be able to access to it from anywhere
As a solution create class user
public class User {
username, full name ...
}
Create embiend class ApplicationContext
public class ApplicationContext
{
private ApplicationContext(){
}
public User UserInfo {get;}
public static ApplicationContext Current{get;}
public static Init(User userInfo)
{
if(Current != null)
throw new Exception("Context already initialized");
Current = new ApplicationContext(){
UserInfo = userInfo
}
}
}
After login call
ApplicationContext.Init(userInfo);
Everywhere where you need user info call
ApplicationContext.Current.UserInfo
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
How can I add items to my comboBox which is in Form1, but the funcion that add items to that combo box is in another class ?
public void comboBox1_Categories_Load()
{
SqlConnection con = new SqlConnection(connection_string);
string select_string = "SELECT * FROM dbo.Categories";
SqlCommand cmd = new SqlCommand(select_string, con);
SqlDataReader myReader;
con.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
comboBox1.Items.Add(myReader[1]);
}
myReader.Close();
con.Close();
}
Form:
public partial class Form1 : Form
{
private BusinessLayer _businessLayer ;
public Form1()
{
InitializeComponent();
_businessLayer = new BusinessLayer();
}
private void button1_Click(object sender, EventArgs e)
{
var categories = _businessLayer.GetCategories();
comboBox1.DataSource = categories;
}
}
Business Class:
class BusinessLayer
{
private DataLayer _dataLayer;
public BusinessLayer()
{
_dataLayer = new DataLayer();
}
internal List<string> GetCategories()
{
return _dataLayer.RetrieveCatagories();
}
}
Data Layer (you can refactor and extract the connection to another method):
class DataLayer
{
public const string ConnectionString = "my connection string";
internal List<string> RetrieveCatagories()
{
List<string> items = new List<string>();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
string select_string = "SELECT * FROM dbo.Categories";
SqlCommand cmd = new SqlCommand(select_string, con);
con.Open();
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
items.Add(myReader[1].ToString());
}
myReader.Close();
}
return items;
}
}
You can something like this:
public static OtherClass()
{
public void RetrieveData(ComboBox comboBox)
{
SqlConnection con = new SqlConnection(connection_string);
string select_string = "SELECT * FROM dbo.Categories";
SqlCommand cmd = new SqlCommand(select_string, con);
SqlDataReader myReader;
con.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
comboBox.Items.Add(myReader[1]);
}
myReader.Close();
con.Close();
}
}
//then the class where your form is
public void comboBox1_Categories_Load()
{
OtherClass.RetrieveData(comboBox1);
}
Please see the code below, it is MVC, I'm trying to create a IEnumerable view. The error I'm getting is'not all code path return a value' how can I correct the error?
public class CustomerSummary
{
public string ContactName { get; set; } // Customer table
public string City { get; set; } // Customer table
public string PostalCode { get; set; } // Order table
public string ShipName { get; set; } // Order table
public string ProductName { get; set; } // Product table
public bool Discontinued { get; set; } // product table
}
Controller
public class CustomerSummaryController : Controller
{
//
// GET: /CustomerSummary/
private CustomerSummaries _customerSummaries = new CustomerSummaries();
public ViewResult Index()
{
IEnumerable<CustomerSummary> summaries = _customerSummaries.GetAll();
return View(summaries);
}
}
Data layer
public IEnumerable<CustomerSummaries> GetAll(/* to do put connection string here */)
{
try
{
SqlCommand cmd = new SqlCommand("GetAll", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader sdr;
conn.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
if (sdr.IsDBNull(sdr.GetOrdinal("ContactName")) != true)
{
sdr["ContactName"].ToString();
}
}
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}
}
I'm making a fair amount of assumptions here, but I think this is what you want:
public IEnumerable<CustomerSummary> GetAll(SqlConnection conn)
{
var result = new List<CustomerSummary>();
try
{
SqlCommand cmd = new SqlCommand("GetAll", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader sdr;
conn.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
var cs = new CustomerSummary();
if (sdr.IsDBNull(sdr.GetOrdinal("ContactName")) != true)
{
cs.ContactName = sdr["ContactName"].ToString();
}
// repeat the above if-block to add more info if needed...
// add the CustomerSummary to the result
result.Add(cs);
}
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}
return result;
}
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;
}