I've a database project , and i'm needed to add elements from database to checklist box,, how can i do that??
this is the code i have written but its seems that it has a problem
private void CheckedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string connection_string = #"Data Source=DESKTOP-MMHA4KL;Initial Catalog=Movie rental;Integrated Security=True";
SqlConnection connection = new SqlConnection(connection_string);
string Add_to_checkbox = "SELECT name from [Actor]";
SqlCommand comm = new SqlCommand(Add_to_checkbox, connection);
connection.Open();
SqlDataReader read_name = comm.ExecuteReader();
int lastindex = 0;
while(read_name.Read())
{
string name = read_name.ToString();
checkedListBox1.Items.Add(name);
}
}
Even though there is only one field being selected in your query, you need to specify it in the read. try
string name = read_name["name"].ToString();
Related
I have a dropdownlist in my project that get the value from SQL Server. Table in SQL Server has several columns and I select MemberId and MemberName from that. I want to show MemberName in the dropdown, but when I select an item, I want to get MemberId.
I do this like that:
string strsql1;
SqlConnection con1;
string strcon = "Data Source=ZAHRA\\SQLEXPRESS01;Initial Catalog=YekAye;Integrated Security=True";
con1 = new SqlConnection(strcon);
strsql1 = "SELECT MemberId,MemberName FROM TbAye WHERE StatusMember = 1 ORDER BY MemberName";
SqlCommand cmd1 = new SqlCommand(strsql1, con1);
con1.Open();
DropDownListAye.DataSource = cmd1.ExecuteReader();
DropDownListAye.DataTextField = "MemberName";
DropDownListAye.DataValueField = "MemberId";
DropDownListAye.DataBind();
con1.Close();
But this:
int SelectedMember = Convert.ToInt32(DropDownListAye.SelectedValue);
gets me the index of the selected item, not MemberId of it.
What should I do?
I found What happened.
I write this:
int SelectedMember = Convert.ToInt32(DropDownListAye.SelectedValue);
in the page_load but I should write it in :
protected void DropDownListAye_SelectedIndexChanged(object sender, EventArgs e)
{
int SelectedMember = Convert.ToInt32(DropDownListAye.SelectedValue);
}
So I'm trying to create sort of an overview utility of sites, with different infos on each site.
I'd like to have a dropdown list / combobox, reading a sqldb and create items according to the db. Then I would like different textboxes to get populated with a value from a column.
Say my db table is called "AvSites" so far (just for the sake of it) i have "projectNr", "siteName", "siteClients" and "siteLicenses" columns I'd like each of these to populate some textbox / label somewhere.
I've tried the following, which kinda works, Ive had the code working most of the time, but the thing that defeats me is having the data change with the combobox item selected.
I hope you can help, and so here is my code so far (I have a login window, before this "main" program starts, just so you're not wondering)
And I'm quite new to C# so if there's something thats done inefficient thats the reason :) Im still learning.
namespace AvOverview{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
//btn_LogOut Click Event
this.Hide();
Form1 fl = new Form1();
fl.Show();
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void FrmMain_Load(object sender, EventArgs e)
{
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf";
SqlConnection con = new SqlConnection(cs);
con.Open();
string strCmd = "select * from AvSites";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
combo1.ValueMember = "id";
combo1.DisplayMember = "siteName";
combo1.DataSource = ds.Tables[0];
combo1.Enabled = true;
this.combo1.SelectedIndex = -1;
cmd.ExecuteNonQuery();
con.Close();
}
private void Combo1_SelectedIndexChanged(object sender, EventArgs e)
{
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf";
string strCmd = "select id from AvSites";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(strCmd, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{//this last part is solely for testing if the text changed the way I wanted.
label1.Text = dr.GetValue(1).ToString();
label2.Text = dr.GetValue(2).ToString();
label3.Text = dr.GetValue(0).ToString();
label4.Text = dr.GetValue(3).ToString();
You don't need to call the database again. All the info are in the current selected item.
When you set the DataSource of your combo to a datatable like you do in the click event each element of the combo is a DataRowView and from this element you can get all the info extracted from the database from your initial query
private void Combo1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView rv = Combo1.SelectedItem as DataRowView;
if(rv != null)
{
label1.Text = rv[1].ToString();
label2.Text = rv[2].ToString();
label3.Text = rv[0].ToString();
label4.Text = rv[3].ToString();
}
}
Side note: There are some improvements needed in your code.
First you should store the connection string in the config file and read it back with the ConfigurationManager class. Read about Configuration in NET
Second you shouldn't work with disposable objects like you do now. A disposable object should be disposed as soon as you have finished to use it. In particular the SqlConnection keeps valuable system resources both on your machine and on the server. You should start to use the using statement
string strCmd = "select * from AvSites";
using(SqlConnection con = new SqlConnection(.......))
using(SqlCommand cmd = new SqlCommand(strCmd, con)))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
combo1.ValueMember = "id";
combo1.DisplayMember = "siteName";
combo1.DataSource = ds.Tables[0];
combo1.Enabled = true;
this.combo1.SelectedIndex = -1;
// ??? not needed ==> cmd.ExecuteNonQuery();
// not needed with using ==> con.Close();
}
// Here the connection is closed and disposed and resources are released
How do I link textboxes?
Scenario:
TextBox_Supplier
TextBox_Address
TextBox_Supplier is autocomplete and it's working. When typing is done in TextBox_Supplier, the TextBox_Address will select supplier's address.
My code does not work:
private void txb_vendor_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txb_address.Text))
{
PurCon.con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = PurCon.getcon();
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("SELECT address FROM tbl_Supplier WHERE supplier_name = {0}",txb_vendor.Text);
SqlDataReader red = cmd.ExecuteReader();
while (red.Read())
{
string address = red.GetString(0);
address = txb_address.Text;
}
PurCon.con.Close();
}
}
Thank you for helping me!
instead of
address = txb_address.Text;
write
txb_address.Text = address;
Try to use Parameterized Query instead of concatenation of the strings.
Do Change as #Mohit suggested and also wrap the supplier name with single quotes, since supplier name is string type and in sql String should be wrap in single Quotes other wise this will give SQL Error
"SELECT address FROM tbl_Supplier WHERE supplier_name = '{0}'"
----^
I already solved this problem last week. And I'm so angry to myself!
The textbox_Address does not changed once, it stacks up when the textbox_Supplier_TextChaged. So I put Clear() method to clear previous input address.
public void AddressTbxLoad()
{
DBCon PurCon = new DBCon();
PurCon.con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = PurCon2.con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("SELECT address FROM tbl_Supplier WHERE supplier_name LIKE '{0}%'", cbx_vendor.Text);
SqlDataReader red = cmd.ExecuteReader();
while (red.Read())
{
string address = red.GetString(0);
txb_address.Text = address;
}
PurCon.con.Close();
}
private void cbx_vendor_SelectedIndexChanged(object sender, EventArgs e)
{
txb_address.Clear();
AddressTbxLoad();
}
private void Purchase_Load(object sender, EventArgs e)
{
VendorTbxLoad();
}
On click button presents the following code,
For some reason it wont delete data from database, (the dropdownlist is valid) any advice or changes needed?
protected void deleteback_Click(object sender, EventArgs e)
{
// declare variables
String EditNewID = DropDownList3.SelectedItem.Value;
// set connection string to database
String connectionString = WebConfigurationManager.ConnectionStrings["ScrumString"].ConnectionString;
SqlConnection myConnection2 = new SqlConnection(connectionString);
// delete values to product backlog
myConnection2.Open();
String query = "DELETE * FROM product_backlog WHERE product_backlog.id = #id ";
SqlCommand commanddelete = new SqlCommand(query, myConnection2);
commanddelete.Parameters.AddWithValue("#id", EditNewID);
// refresh page
Page.Response.Redirect(Page.Request.Url.ToString(), true);
commanddelete.ExecuteNonQuery();
myConnection2.Close();
}
maybe you are creating one string ID instead an integer
Try something like
commanddelete.Parameters.Add("#id", SqlDbType.Int);
commanddelete.Parameters["#id"].Value = Int32.Parse(customerID);
I have the label:
<asp:Label ID="lbl1" runat="server"></asp:Label>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
lbl1.Text = ImageCheck().ToString();
}
And:
protected int ImageCheck()
{
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\***.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
string CommandText2 = "SELECT * FROM Machreta WHERE noImage = 1";
SqlCommand command2 = new SqlCommand(CommandText2, connection);
connection.Open();
int check = (int)command2.ExecuteScalar();
connection.Close();
return check;
}
How can i return multiple values? That label display only single value but there are 6 more in the table.
try this:
protected string ImageCheck()
{
var result = new StringBuilder();
using(var connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\***.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"))
{
string CommandText2 = "SELECT * FROM Machreta WHERE noImage = 1";
SqlCommand command2 = new SqlCommand(CommandText2, connection);
connection.Open();
using(var reader = command2.ExecuteReader())
{
while (reader.Read())
{
result.Append(reader.GetString(0));
}
}
return result.ToString();
}
}
of course is only an example and not fully solving your issue but should be a starting point :)
Here is the explanation of ExecuteScalar() method. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.71%29.aspx
"Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored."
Also, SELECT * will fetch all the columns. You probably want to display multiple values for single column. Then select the column name in select statement.
SELECT xyzColumn FROM Machreta WHERE noImage = 1
Lastly, you can assign only one string to label.text. So, you will have to concatenate all these strings (multiple values for single column) and then assign it to label text. Use a reader and ExecuteReader() method instead of ExuecuteScalar().