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.
Related
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.
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");
I have a table from a database, i want display a value from table to my label1. This is my code:
string query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";
SqlConnection con = new SqlConnection(query);
con.Open();
string query1 = "select prodName from ProductMaster where #name='Bar Counter' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
label1.Text = dr.GetValue(1).ToString();
textBox1.Text = dr.GetValue(0).ToString();
}
but after that, i must click on this label to display the value. What can i do with this code to display my value in label while don't need click to anything?
As #wqrahd said
protected void Page_Load(object sender, EventArgs e)
{
string query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";
SqlConnection con = new SqlConnection(query);
con.Open();
string query1 = "select prodName from ProductMaster where #name='Bar Counter' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
label1.Text = dr.GetValue(1).ToString();
textBox1.Text = dr.GetValue(0).ToString();
}
place this code in page_load method of your WinForm.
Write a different function with your code and call it in page_load events and other events if required:
protected void Page_Load(object sender, EventArgs e)
{
setLableText();
}
private void setLableText()
{
string query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";
SqlConnection con = new SqlConnection(query);
con.Open();
string query1 = "select prodName from ProductMaster where #name='Bar Counter' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
label1.Text = dr.GetValue(1).ToString();
textBox1.Text = dr.GetValue(0).ToString();
}
}
If this is for the web application:
In order to show the label as soon as user opens the page.
You must write the code in page load.
Also If you want to display this Label only the first time and after that value changes over some event, then place the code as:
..Page_Load(..)
{
(!IsPostBack)
{
}
}
So that Label shows value first time page loads.
Any doubt you can ask again. :)
For window application logic remains the same.
private void label1_Click_1(object sender, EventArgs e) {}
call on Page Load like:
Page_Load(...)
{
label1_Click_1(null, null);
}
I would like ask if you could help me with my codes as I don't get the result that I want which is to load the details of a particular paper from drop down list.
Currently, when the page loads, the details of the selected item will load up. But when I try to choose another item from the drop down list, corresponding details won't show up, the previous one still remains instead.
Under the properties of drop down list, I also set autopostback to yes so that it will automatically load the corresponding details of the item selected.
Please see codes below
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetPaper();
GetInk();
GetPaperDetails(ddlPaperName.SelectedItem.Value);
//pnlPrinting.Visible = true;
}
}
protected void btnCompute_Click(object sender, EventArgs e)
{
}
protected void btnCancel_Click(object sender, EventArgs e)
{
}
private void GetPaper()
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Papers";
SqlDataReader data = com.ExecuteReader();
ddlPaperName.DataSource = data;
ddlPaperName.DataValueField = "PaperID";
ddlPaperName.DataTextField = "PaperName";
ddlPaperName.DataBind();
data.Close();
con.Close();
}
private void GetPaperDetails(string paper)
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Papers WHERE PaperID=" + paper;
SqlDataReader data = com.ExecuteReader();
while (data.Read())
{
lblPaperPrice.Text = data["PaperPrice"].ToString();
lblDescription.Text = data["PaperDescription"].ToString();
lblSpecification.Text = data["PaperSpecification"].ToString();
imgPaper.ImageUrl = "../" + data["PaperImage"].ToString();
}
data.Close();
con.Close();
}
private void GetInk()
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Inks";
SqlDataReader data = com.ExecuteReader();
ddlPaperName.DataSource = data;
ddlPaperName.DataValueField = "InkID";
ddlPaperName.DataTextField = "InkName";
ddlPaperName.DataBind();
while (data.Read())
{
lblInkPrice.Text = data["InkPrice"].ToString();
}
data.Close();
con.Close();
}
protected void ddlPaperName_SelectedIndexChanged(object sender, EventArgs e)
{
GetPaperDetails(ddlPaperName.SelectedItem.Value);
}
Looking forward to your feedback here. Thanks!
Set AutoPostBack property to true of your drop down list.
us this code, for that,
if (!IsPostBack == true)
{
drpdownaccountnamebind();
drpdowncountrynamebind();
}
i hope this will be helpful,
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (s.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
rdr.Close();
}
catch
{
conn.Close();
}
}
I have a button like this. But I'm not able to get the values of the cells(Label is not getting appended).
protected void Button1_Click(object sender, EventArgs e)
{
string[] FID={};
int j=0;
foreach (GridViewRow di in GridView1.Rows)
{
HtmlInputCheckBox chkBx = (HtmlInputCheckBox)di.FindControl("CheckBox1");
if ( chkBx != null && chkBx.Checked)
{
FID[j] += di.Cells[2].Text;
j++;
Label1.Text += di.Cells[2].Text;
//Label lbl = (Label)di.FindControl("Id");
//Response.Write(lbl.Text + "<br>");
}
}
}
Put your page load code under if(!IsPostBack){yourCode....} so when you click the button your page load event will be called before the click handler and it will rebind the gridview.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (s.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
rdr.Close();
}
catch
{
conn.Close();
}
}
}
i think if you can debug the code,
you can find and solve your problem easily.
First, check is your loop really do.
Second, is Cell[2] is really what you want to get data.(I doubt that)
Hope it works!