changing value of cell on condition in gridview - c# - 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;
}

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();
}
}
}

Not getting any row data from database using c# asp.net.

I can not get any row data from database using c# asp.net.I am trying to fetch one row data from my DB but it is not returning any row.I am using 3-tire architecture for this and i am explaining my code below.
index.aspx.cs:
protected void userLogin_Click(object sender, EventArgs e)
{
if (loginemail.Text.Trim().Length > 0 && loginpass.Text.Trim().Length >= 6)
{
objUserBO.email_id = loginemail.Text.Trim();
objUserBO.password = loginpass.Text.Trim();
DataTable dt= objUserBL.getUserDetails(objUserBO);
Response.Write(dt.Rows.Count);
}
}
userBL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
userDL objUserDL = new userDL();
try
{
DataTable dt = objUserDL.getUserDetails(objUserBO);
return dt;
}
catch (Exception e)
{
throw e;
}
}
userDL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
SqlConnection con = new SqlConnection(CmVar.convar);
try
{
con.Open();
DataTable dt = new DataTable();
string sql = "SELECT * from T_User_Master WHERE User_Email_ID= ' " + objUserBO.email_id + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(dt);
con.Close();
return dt;
}
catch(Exception e)
{
throw e;
}
}
When i am checking the output of Response.Write(dt.Rows.Count);,it is showing 0.So please help me to resolve this issue.
It looks like your your query string has a redundant space between ' and " mark. That might be causing all the trouble as your email gets space in front.
It is by all means better to add parameters to your query with use of SqlConnection.Parameters property.
string sql = "SELECT * from T_User_Master WHERE User_Email_ID=#userID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#userID", SqlDbType.NVarChar);
cmd.Parameters["#userID"].Value = objUserBO.email_id;

Accessing Listview index above index 9 in C#?

I have a Listview control that displays data which has 12 columns. From column 1 to 9 it displays, but above 9 it doesn't displays the data even the index number is provided.
Check out bellow code which has indexes to display for all columns. Also See the above pic:
public void populateProductList()
{
string cmdString = "SELECT * FROM PRODUCT";
StockDbConnection dbcon = new StockDbConnection();
SqlCeConnection Conn = new SqlCeConnection(dbcon.ReturnConnection("ConnString"));
SqlCeCommand cmd = new SqlCeCommand(cmdString, Conn);
try
{
Conn.Open();
SqlCeDataReader dr = cmd.ExecuteReader();
lstvwProduct.Items.Clear();
while(dr.Read())
{
ListViewItem obj=new ListViewItem();
obj.SubItems[0].Text = dr[0].ToString();
obj.SubItems.Add(dr[1].ToString());
obj.SubItems.Add(dr[2].ToString());
obj.SubItems.Add(dr[3].ToString());
obj.SubItems.Add(dr[4].ToString());
obj.SubItems.Add(dr[5].ToString());
obj.SubItems.Add(dr[6].ToString());
obj.SubItems.Add(dr[7].ToString());
obj.SubItems.Add(dr[8].ToString());
obj.SubItems.Add(dr[9].ToString());
obj.SubItems.Add(dr[10].ToString());
obj.SubItems.Add(dr[11].ToString());
//in object of ListViewItem give display member at first and give value member at second position
lstvwProduct.Items.Add(obj);
// add object to the listbox
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
The problem is: index 10 and 11 doesn't display, I already have the column collection for them.
You just try it by assigning a dataset to Gridview's datasource property.
it will be more helpful to you.
public void populateProductList()
{
string cmdString = "SELECT * FROM PRODUCT";
StockDbConnection dbcon = new StockDbConnection();
SqlCeConnection Conn = new SqlCeConnection(dbcon.ReturnConnection("ConnString"));
SqlCeCommand cmd = new SqlCeCommand(cmdString, Conn);
DataSet ds;
try
{
Conn.Open();
SqlCeDataAdapter da = new SqlCeDataAdapter(cmdString, Conn);
da.fill(ds);
lstDGView.DataSource=ds;
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}

Update sql database using dataset

I need some help to complete this. I have searched and tried several ways but is not enetring in my head yet. It is not homework! I am a self learner.
I managed to populate a grid selecting the table from a dropdown:
private void radDropDownList1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
if (radDropDownList1.SelectedIndex > 0)
{
radGridView1.Visible = true;
label8.Text = radDropDownList1.SelectedValue.ToString();
DataTable dt = new DataTable();
var selectedTable = radDropDownList1.SelectedValue; //Pass in the table name
string query = #"SELECT * FROM " + selectedTable;
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
radGridView1.DataSource = dt;
}
Now I am trying to write the event to update the sql table using the grid as datasource:
private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
{
DataTable dt = (DataTable)radGridView1.DataSource;
DataSet ds = new DataSet();
ds.Tables[0] = dt;
try
{
//**I am lost here!**
}
catch
{
}
}
Could you please help? How can I now update the sql table?
I don't really like the way you are managing the updates but... this code here will send an update statement:
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("UPDATE YourTable SET Column = #Parm1 WHERE Col = #Parm2", cn);
var parm1 = cmd.CreateParameter("Parm1");
parm1.Value = "SomeValue";
var parm2 = cmd.CreateParameter("Parm2");
parm2.Value = "SomeOtherValue";
cmd.Parameters.Add(parm1);
cmd.Parameters.Add(parm2);
int rowsAffected = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}

Fill ComboBox with Access DB data

I'm using Visual Studio 2010 and C# to create a windows form with a combobox that should contain employees initials. I have spent the last few days searching through every solution I can find and I still can not get my combobox to populate.
This is what I've got as of now:
public static void FillComboBox(string Query, System.Windows.Forms.ComboBox LoggedByBox)
{
using (var CONN = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Documents\\Service Request Application\\bin\\Debug\\servicereq1.mdb"))
{
CONN.Open();
DataTable dt = new DataTable();
try
{
OleDbCommand cmd = new OleDbCommand(Query, CONN);
OleDbDataReader myReader = cmd.ExecuteReader();
dt.Load(myReader);
}
catch (OleDbException e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
LoggedByBox.DataSource = dt;
LoggedByBox.ValueMember = "ID";
LoggedByBox.DisplayMember = "Initials";
}
}
Then I call it when the form loads
private void Form1_Load(object sender, EventArgs e)
{
FillComboBox("select ID, Initials from [Fixers and Testers]", LoggedByBox);
}
When I run the program, the combobox is still blank. I'm positive that my column names and table names are correct. Any suggestions?
I finally got my ComboBox filled and I wanted to share what I changed for anyone else who stumbles across this question in their searches. After spending a bit more time searching through other questions and MSDN, I was able to come up with this.
private void LoadComboLogged()
{
AppDomain.CurrentDomain.SetData("DataDirectory",#"\\prod\ServiceRequests");
string strCon = #"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|\servicereq1.mdb";
try
{
using (OleDbConnection conn = new OleDbConnection(strCon))
{
conn.Open();
string strSql = "SELECT Initials FROM [Fixers and Testers] WHERE [Status] ='C'";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
DataSet ds = new DataSet();
adapter.Fill(ds);
loggedByComboBox.DataSource = ds.Tables[0];
loggedByComboBox.DisplayMember = "Initials";
loggedByComboBox.ValueMember = "Initials";
}
}
catch (Exception ex)
{
}
}
I also found that I needed to call
LoadComboLogged();
when I initialized my form. Without that line, the ComboBox would only show a blank dropdown list. Hope this helps someone else who runs into this problem.
Passing control to static method causing this issue. Instead of passing control to the method make that method returns the table and within the load method load the control.
SqlConnection con = new SqlConnection("Data Source=RUSH-PC\\RUSH;Initial Catalog=Att;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select name from userinfo", con);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr;
dr = dt.NewRow();
dt.Rows.InsertAt(dr, 1);
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "name";
comboBox1.DataSource = dt;
con.Close();
This may help you...
Good luck...:-)
Another possible solution would be to query and return a list of strings. Perhaps it may be less efficient, but it's what I used in a recent project of mine. Here's an example that would reside in a method, possibly called GetInitialsFromDatabase():
using(var conn = new MySqlConnection(connectionString)
{
conn.Open();
using(MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT Initials FROM [Fixers and Testers] WHERE [Status] ='C'";
MySqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
// initials is a List<String> previously defined (Assuming strings)
initials.Add(String.Format("{0}", reader[0]));
}
}
conn.Close();
}
And then return the initials List, and then in your GUI you could say:
comboBox1.DataSource = returnedList;
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

Categories