C#: how to add 2 values in ComboBox from stored procedure - c#

I have TWO questions, first how to add 2 values and second is: if we add 2 values so we need to change the code when we save combo-box value in database (second question with code I also ask from end of this question)?
I need to add 2 values from table dep_Id and dep_Name in `ComboBox; like this:
(Department ID: Department Name)
This is the stored procedure:
CREATE PROCEDURE [dbo]. SelectComoboxData_SP
AS
SELECT dep_Id, dep_Name
FROM department
RETURN 0
This is the C# code:
public void updateDepartmentList()
{
refresh_DataGridView();
SqlCommand cmd = new SqlCommand("SelectComoboxData_SP", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
com_boxDepartment.Items.Add(dr["dep_Id"]);
com_boxDepartment.SelectedIndex = 0;
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show("<<<INVALID SQL OPERATION \n" + ex);
}
con.Close();
}
Let me also know when I select any department from the combobox so now I wrote this code
cmd.Parameters.AddWithValue("#dId", com_boxDepartment.Text);
for saving by id, so when add 2 values in combobox so we need to change anything?

If it were my C# I'd do it more like this (though I'd use strongly typed datasets)
public void updateDepartmentList()
{
refresh_DataGridView();
SqlCommand cmd = new SqlCommand("SelectComoboxData_SP", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
com_boxDepartment.DataSource = dt;
com_boxDepartment.DisplayMember = "dep_Name";
com_boxDepartment.ValueMember = "dep_Id";
}
Your combo will show "History Department" for example, but when you ask it for the .SelectedValue it will return e.g. 2 (the id for the history department)

Related

c# function for filling ComboBox

I Want to create a function in ClassProducts.cs file and when I call that function it should return Values & Tags for that ComboBox.
ComboBox Control is in ViewProducts Form and function in ClassProducts.cs class. Function accepts 1 parameter called Cat_ID
class ClassProducts
{
public DataTable FillSubCats(int catID)
{
DataTable items = new DataTable();
SqlCommand cmdFillSubCatL1 = new SqlCommand("SELECT * FROM tblProductCategories WHERE Cat_ParentCat =" + catID, con);
con.Open();
SqlDataReader sda = cmdFillSubCatL1.ExecuteReader();
while (sda.Read())
{
ComboboxItem item = new ComboboxItem();
item.Text = (sda["Cat_Name"]).ToString();
item.Value = (sda["Cat_ID"]).ToString();
items.Load(sda);
}
sda.Dispose();
sda.Close();
con.Close();
return items;
}
}
I want a function in ClassProducts file which will be filling ComboBoxes in ViewProducts.cs Form. Whenever function called it should return combo box items to the calling file.
I have tried this function but it is not working.
Please help.
Thank You.
This is most probably due to the fact that you are not using sqlparameters. Cat_ParentCat must be an int field so when you try to use query with string concatenation, a cats to nvarchar field is taking place, and since you don't wrap catId with quotes on your query, it fails . In any case using SQL Parameters, will also help you avoid SQL injection. Try:
SqlCommand cmdFillSubCatL1 = new SqlCommand("SELECT * FROM tblProductCategories WHERE Cat_ParentCat =#catId", con);
cmdFillSubCatL1.Parameteres.Add("#catId",SqlDbType.Int).Value=catId;
...
EDIT:
After Correct comment, a better query should be:
"SELECT Cat_Name,Cat_ID FROM tblProductCategories WHERE Cat_ParentCat =#catId"
Finally since you want to load a DataTable don't use Datareader but a dataAdapter:
...
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmdFillSubCatL1 ;
adapter.Fill(items );
How about this. I have added a method FillSubCatsProxy which should simulate what your method is returning.:
public Form1()
{
InitializeComponent();
comboBox1.DataSource = FillSubCatsProxy(1);
comboBox1.DisplayMember = "Cat_Name";
comboBox1.ValueMember = "Cat_ID";
comboBox1.SelectedIndexChanged += (s, e) => { MessageBox.Show("Selected:" + comboBox1.SelectedValue); };
}
public DataTable FillSubCatsProxy(int catID)
{
var dt = new DataTable();
dt.Columns.Add("Cat_Name");
dt.Columns.Add("Cat_ID");
dt.Rows.Add("Fish","1");
dt.Rows.Add("Jack","2");
return dt;
}
public DataTable FillSubCats(int catID)
{
SqlConnection con = new SqlConnection("Somewhere");
try
{
con.Open();
DataTable items = new DataTable();
var da = new SqlDataAdapter("SELECT Cat_Name,Cat_ID FROM tblProductCategories WHERE Cat_ParentCat = " + catID, con);
da.Fill(items);
return items;
}
finally
{
con.Close();
}
}
}

changing value of cell on condition in gridview - c#

I have fetched the data from SQL server to datagridview but I don't know how to change the cell value. I have to change the fetched value 1 and 0 to available and unavailable. here is my code for fetching data ... please help.
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
SqlCommand cmd = new SqlCommand("Select id as 'Book ID',name as 'Name' , status as 'Status' from book where Name = #name", con);
cmd.Parameters.AddWithValue("#name", txtFirstName.Text);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
dataGridView1.DataSource = bsource;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
Please find below answer
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
string sSql=#"Select id as 'Book ID',name as 'Name' ,
Case when status=0 then 'unavailable' else 'available '
End as 'Status' from
book where Name ='"+txtFirstName.Text +"'"
SqlCommand cmd = new SqlCommand(sSql, con);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
First of all, try to store your queries in variables. This will help you in the long run. Also, it is good practise to check whether you are connected or not before trying to send a query away to the server. It is important to remeber that when you fetch data from your server, it will most likely be seen as a string, so if you want to compare it as a number, you need to convert it first.
What you could do is something similar to what i've written below. You count the amount of answers your query returns, then loop through them and check whether they are 0 or 1. Then just replace the value with Avaliable or Unavaliable.
if (dbCon.IsConnect()){
MySqlCommand idCmd = new MySqlCommand("Select * from " + da.DataGridView1.Text, dbCon.Connection);
using (MySqlDataReader reader = idCmd.ExecuteReader()){
// List<string> stringArray = new List<string>(); // you could use this string array to compare them, if you like this approach more.
while (reader.Read()){
var checkStatus= reader["Status"].ToString();
Console.WriteLine("Status: " + checkStatus.Split(' ').Count()); //checks how many items you've got.
foreach (var item in checkStatus.Split(' ').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray()){
var item2 = 0.0; // your 0 or 1 for avaliable or unavaliable..
try{
item2 = double.Parse(item.ToString());
if(strcmp(item2,'0') == 1){ //assuming you only have 0's and 1's.
item2 = "unavaliable";
}else{
item2 = "avaliable";
}
}
catch (Exception){
//do what you want
}
Console.WriteLine("item: " + item2);
}
}
dbCon.Close();
}
}
return //what you want;
}

display data to listbox C#

Listbox does not show data. Verified data is in database and I am not getting an
error. Not sure where/what is wrong. Thanks in advance. My code is attached.
private void UpDateList()
{
// add data connection and fill data set.
SqlConnection conn = new SqlConnection(dataSource);
DataTable dt = new DataTable();
string sqlString = "select * from Suppliers";
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = sqlString;
da.Fill(ds);
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
foreach(DataRow dRow in ds.Tables[0].Rows)
{
ArrayList values = new ArrayList();
foreach(object value in dRow.ItemArray)
{
values.Add(value);
_Suppliers.Add(values);
}
}
lstSuppliers.DataSource = _Suppliers;
lstSuppliers.Update();
}
It's kinda pointless to enumerate one bindable data collection and transfer data into another bindable collection so it can be bound. Just have your list use the default view of the datatable that already holds the data (allows sorting, filtering etc)
E.g.
LstSuppliers.DataSource = ds.Tables[0].DefaultView;
LstSuppliers.DisplayMember = "column name goes here of what to show eg SupplierName";
LstSuppliers.ValueMember = "column whose value to use for lstSuppliers.SelectedValue e.g. supplierId";
And then for example, not required but an example possibility:
ds.Tables[0].DefaultView.Sort = "[SupplierName] ASC";

How to arrange the FieldName in AspxGridView?

I want to arrange the Field Names as user wants to display. I am not using SqlDataSource. I am calling the stored procedure by programming like below.
string cs = ConfigurationManager.ConnectionStrings["HQMatajerConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetTotalSalesQuantity",con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DateFrom", DateFromStr);
cmd.Parameters.AddWithValue("#DateTo", DateToStr);
//cmd.Parameters.AddWithValue("#DateFrom", "2015-01-01 00:00:00");
//cmd.Parameters.AddWithValue("#DateTo", "2015-12-31 23:59:59");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
}
In result, I can see the field name how i have given the Column_name in my query. But, User wants to see the Field Name how they are arranging.
For Example:
select
student_id,student_name ,Class,School_Name
From
Student_Details
If above one is my stored procedure. I will get the Field Name how I mentioned in my query.
But User wants to see the result how they are giving. If user give School_Name,Class,Student_id,School_Name.
Is there anyway to arrange in AspxGridView?
Check my answer Based on my understanding of the question and #mohamed's comment.
Try to use the DataColumn.SetOrdinal method. For example:
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
ds.Tables[0].Columns["School_Name"].SetOrdinal(0);
ds.Tables[0].Columns["Class"].SetOrdinal(1);
ds.Tables[0].Columns["Student_id"].SetOrdinal(2);
ds.Tables[0].Columns["School_Name"].SetOrdinal(3);
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
even if user changes the select statement order of columns will not change.
Use the hiddentext field and get the column names as user wants to display in which order.
string selectedColumns = HiddentxtSelectedColumn.Value;
Move the selectedColumns to array
string[] names = selectedColumns.Split(',');
sda.Fill(ds);
for (int i = 0; i < names.Length; i++)
{
ds.Tables[0].Columns[names[i]].SetOrdinal(i);`
}
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
Now It will run exactly.

How to get the data when I select a datagridview cell or column

I have 2 datagridview controls in a Windows Forms application.
I would like to get the info of a person when I select first datagridview cell or row to next datagridview:
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
adap3 = new SqlDataAdapter(#"SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id='"+DailyGV.CurrentRow+"'", con);
ds3 = new DataSet();
adap3.Fill(ds3, "dailyattendance");
dataGridView1.DataSource = ds3.Tables[0];
}
Im trying the above code. But it's not working.
I'm not too sure what DailyGV.CurrentRow is but basically you can use the RowHeaderMouseClick...see MSDN documentation. To use it, hook an event handler to it when initializing the form components (you can use VS designer as well...
dataGridView1.RowHeaderMouseClick += dataGridView1_RowHeaderMouseClick;
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
}
this event handler will get fired everytime you select a row header in the DataGridView control which will pass information about the event through an instance of the DataGridViewCellMouseEventArgs class (see MSDN documentation). This argument has a RowIndex property that provides the index of the row clicked which you can use to retrieve the values of the cells in that row...including the person id (if provided)...for example...
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
string personId = dataGridView1.Rows[e.RowIndex].Cells["PersonId"].Value;
//TODO: implement your own query to retrieve data for that person id
}
notice that you need to provide a proper column name when access the cells collection indexer...Cells["columnName"]
I will not give any description about the solution because Leo and Arsalan Bhatti has already suggested the solution. I am just telling you how your code should looks like and how it should be written.
string connectionString = consettings.ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
string empID = DailyGV.CurrentRow.Cells["employee_id"].Value.ToString();
SqlCommand Cmd = con.CreateCommand();
Cmd.CommandText = "SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id=#employee_id";
Cmd.Parameters.Add("#employee_id", SqlDbType.Int).Value = Int32.Parse(empID);
adap3 = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
adap3.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
catch
{}
}
try
{
cn.Open();
string query = "select employee_id,Employee_Name,Image_of_Employee from Employee_Details where employee_id='" + dataGridView1.SelectedCells[0].Value.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader sdr;
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
string aa = (string)sdr["employee_id"];
string bb = (string)sdr["employee_name"];
txtEmployeeID.Text = aa.ToString();
txtnameofemployee.Text = bb.ToString();
byte[] img=(byte[])sdr["Image_of_employee"];
MemoryStream ms=new MemoryStream(img);
ms.Seek(0,SeekOrigin.Begin);
pictureBox1.Image=Image.FromStream(ms); cn.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
You are passing the current row's index as employee id in SELECT query. Pass employee id for the selected record. Then it will work fine.

Categories