confused about how populate listview - c#

I have a table with 2 columns: username and age. What I want to do is to populate a ListView with data coming from the database. I think I missed out something because every time the form is loaded the ListView is empty. I have noticed that the DataReader's property HasRows return false while debugging.
void populate()
{
SqlCommand cmd = new SqlCommand("select * from users ", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
ListViewItem lvi = new ListViewItem(dr[0].ToString());
lvi.SubItems.Add(dr[1].ToString());
listView1.Items.Add(lvi);
}
dr.Close();
dr.Dispose();
}
private void button1_Click(object sender, EventArgs e)
{
using (con = new SqlConnection("server=.\\sqlepxress;database=Projects;Integrated Security=sspi")) {
try
{
con.Open();
populate();
}
catch (SqlException x )
{
MessageBox.Show(x.Message);
}
}
}

your Connection string isn't valid, try:
con = new SqlConnection("Data Source=....;Initial Catalog=..;Connect Timeout=15;Integrated Security=sspi";
OR (in case Windows Authendication has problems :)
new SqlConnection("Data Source="+...+";Initial Catalog=Projects;User id="+user+";Password="+pass+";Connect Timeout=15;Integrated Security=false");

Related

How to make a dropdownlist from sql to be displayed in listbox asp.net c#

This is my code and I'm new to C# and trying to learn, basically I have a project where specialists are being scheduled in their specialty using fullcalendar, but when I created the dropdownlist for specialty and then made a listbox for the specialist in each specialty being selected it keeps saying that there's an error on cmd.ExecuteScalar(); What am I doing wrong?
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String CS = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT id, name, active, modifiedDate, note FROM sldb.dbo.Services", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "id";
DropDownList1.DataBind();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if(this.DropDownList1.SelectedItem.Value != "0")
{
String CS = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using(SqlCommand cmd = new SqlCommand("select firstName from sldb.dbo.Specilist where serviceID= #serviceID", con))
{
using(SqlDataAdapter da = new SqlDataAdapter(cmd))
{
cmd.Parameters.AddWithValue("#serviceID", this.DropDownList1.SelectedItem.Value);
con.Open();
object firstName = cmd.ExecuteScalar();
con.Close();
this.ListBox1.Text = firstName.ToString();
}
}
}
}
else
{
this.ListBox1.Text = "Please select name from list";
}
}```
If the error is on ExecuteScalar, there is something wrong with your query. I'm noticing Specialist is spelled wrong in the select statement. Try correcting that and let me know if that helps.
note that executeScalar return the first column of the first row in the dataset. Try wrap the executescalar in a try catch
try
{
object firstName = cmd.ExecuteScalar();
}
catch(Exception error)
{
//display error message error.Message;
}
Step through the code, I'd be tempted to put the value in a string to see what Scalar is returning.
string strPeek = cmd.ExecuteScalar().ToString();
Also, run the SQL separately to be sure the query is not erroneous.

how to delete data from data grid view using ms access in c#

private void Delete_Click(object sender, EventArgs e)
{
//i have used this query for delete button
DataSet ds = new DataSet();
OleDbDataAdapter ad = new OleDbDataAdapter();
OleDbConnection con = new
OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\HP\Desktop\sd.mdb");
con.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\HP\Desktop\sd.mdb";
con.Open();
//this is the query i have used
OleDbCommand cmd = new OleDbCommand("DELETE FROM car_model WHERE Description ='" + des+ "'", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Deleted");
con.Close();
}
//i have table named:car_model & attribute as Description
Your quotes don't look right, but my eyes are not great and anyway, the compiler would pick that up immediately, so I guess it's something else.
private void BtnDelete_Click(object sender, RoutedEventArgs e)
{
DataRowView drv = (DataRowView)dataGridView1.SelectedItem;
int id = drv.Row[0];
if(drv != null)
{
delete(id);
}
}
public void delete(int id)
{
try
{
con.Open();
OleDbCommand comm = new OleDbCommand("Delete From Car_Model Where Description = #Des", con);
comm.Parameters.AddWithValue("#Des", id);
comm.ExecuteNonQuery();
}
catch(OleDbException ex)
{
MessageBox.Show("DataConnection not found!", ex);
}
finally
{
con.Close();
}
Also, use the '#' character to prevent SQL Injection issues. I don't think this is necessarily a problem with MS Access, but it's a good habit to get into.
https://www.w3schools.com/sql/sql_injection.asp

C# loading data from MS Access database to listbox

public partial class Form1 : Form
{
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AsusK450c\documents\visual studio 2010\Projects\ADD\ADD\testing.accdb;Persist Security Info=True";
cmd.Connection = cn;
loaddata();
}
private void loaddata()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
try
{
string q = "select * from info";
cmd.CommandText = q;
cn.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
dr.Close();
cn.Close();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
}
This is an image of the database:
I added 2 list boxes. Those two should display the data i put in the database but It doesn't. I don't know which is wrong, the path, the code or the database
There is nothing wrong with you code. Check if you are getting any exceptions or pointed to the right database.
Also check if you have assigned the function Form1_Load() to form's load event
I'm not sure what your problem is, but you can change the connectionString by this way:
System.Data.OleDb.OleDbConnectionStringBuilder builder = new System.Data.OleDb.OleDbConnectionStringBuilder();
builder.Provider = "Microsoft.ACE.OLEDB.12.0";
builder.OleDbServices = -1;
builder.DataSource = #"C:\Users\AsusK450c\documents\visual studio 2010\Projects\ADD\ADD\testing.accdb";
cn.ConnectionString = builder.ConnectionString;
OleDbServices = -1 can help you.

how to search table through textbox?

I have piece of query that search database from text box.
My question is how can insert search result column by column to separated text box, I mean each column go to one textbox.
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
com.ExecuteNonQuery();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Try this :
private void searchbtn_Click(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection("Your String Connection");
SqlDataAdapter adapter = new SqlDataAdapter(#"Select Name, FileName From Table Where Name Like #Name", sql);
adapter.SelectCommand.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
}
I assume that, your search will return only one row.
You can use datareader to achieve that. I modified your function with below code:
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
SqlCeDataReader sqlReader = com.ExecuteReader();
while (sqlReader.Read())
{
txtID.text = sqlReader.GetValue(0).ToString();
txtRadif.text = sqlReader.GetValue(1).ToString();
txtName.text = sqlReader.GetValue(2).ToString();
}
sqlReader.Close();
com.Dispose();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Note: Your code is vulnerable to sqlinjection. Learn things to avoid it.

Having issue regarding to checklistbox

I have a checkedListBox and a TextBox...When I Checked item in the checkedListBox it shows the value of the respective item in the TextBox...When I Checked multiple items in the checkedListBox it shows the values of the respective items in the TextBox separating by {,}"Comma"
Now my question is that when I unchecked the item in the textBox it must remove the value of respective unchecked items from the textBox ...also please tell me how do I remove "Comma"{,} from the end of the text box programmatically
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=email_client;Integrated Security=True");
SqlCommand command = new SqlCommand("Select * FROM address_book ", connection);
try
{
connection.Open();
{
SqlDataReader drd = command.ExecuteReader();
while (drd.Read())
{
this.checkedListBox1.Items.Add(drd.GetString(0).ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
connection.Close();
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=email_client;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from address_book where name='" + checkedListBox1.Text + "'", con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text += Convert.ToString(dr["id"] + ",");
}
dr.Close();
}
private void textBox1_Enter(object sender, EventArgs e)
{
ToolTip tt = new ToolTip();
tt.SetToolTip(textBox1, "sorry");
}
}
First of all, you should not use SelectedIndexChanged event if you'd like to show "checked" items. Use ItemCheck instead:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
Then use CheckedListBox.CheckedItems to retrive all items which are checked:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (var item in checkedListBox1.CheckedItems)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=email_client;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(string.Format("select * from address_book where name='{0}'", item), con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
stringBuilder.Append(Convert.ToString(dr["id"] + ","));
}
dr.Close();
}
textBox1.Text = stringBuilder.ToString().TrimEnd(',');
}
Remember use string.TrimEnd() to trim the last comma.
Well, this is not the most effective way to do this, because you need to go through each checked item when one of them changed. You could use a Dictionary to maintain name-id pairs -- at least it is no need to execute SQL queries when you unchecked an item, right? :)
To remove ,
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
But I would ideally keep my dr["id"] in a List and create a small function that iterates through the list and return comma separated string. Adding and Removing items should take place in that collection.

Categories

Resources