populate combobox with values from another form - c#

I might ask a stupid question, but I can't find it on the internet.
I have a combobox and I would like to retrieve some data from another form where the info is typed and saved by the user. If anyone is willing to help, I'll be greatful. Thanks
I used this code
string cs = "Data Source=CODRINMA\\CODRINMA;Initial Catalog=BusManager; Trusted_Connection=True;";
string select = "SELECT * FROM TipAutocar";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand(select, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cmbTip.Items.Add(dr["Model", "Type"]);
}
con.Close();
And it worked..but is this possible to get for eg "Model" + "Type"?
And I get this error ->
Error 1 No overload for method 'this' takes 2 arguments

If I understood your question correctly, you want to add different column values to your ComboBox concatenated. So, it's as simple as that:
while (dr.Read())
{
cmbTip.Items.Add(dr["Model"].ToString() + " " + dr["Type"].ToString());
}

Related

Data type mismatch in criteria expression - started only recently

I use Access database. This error wasn't occurring 30 minutes ago.
ERROR is:
Data type mismatch in criteria expression.
OleDbConnection con = new OleDbConnection(Utility.GetConnection());
con.Open();
OleDbCommand cmd2 = new OleDbCommand("INSERT INTO Temsilci(isin_adi,isin_tanimi,verildigi_tarih,teslim_tarihi,sorumlu_marka,sorumlu_ajans,revize,Temsilci_isverenid)
values (#isinadi,#isintanimi,#vertarih,#testarih,#smarka,#sajans,#revize,#temsid)", con);
cmd2.Parameters.Add("isintanimi", txtMarkaAdi.Text);
cmd2.Parameters.Add("isinadi", txtisAdi.Text);
cmd2.Parameters.Add("smarka", txtMarkaTemsilcisi.Text);
cmd2.Parameters.Add("sajans", txtAjansTemsilcisi.Text);
cmd2.Parameters.Add("revize", txtSorumluKisiler.Text);
cmd2.Parameters.Add("vertarih", txtverilisTarihi.Text);
cmd2.Parameters.Add("testarih", txtTeslimTarihi.Text);
cmd2.Parameters.Add("temsid", Session["UserID"]);
cmd2.ExecuteNonQuery();
con.Close();
My database columns are:
ID = AutoNumber
isin_adi = Short Text
isin_tanimi = Long Text
verildigi_tarih= Date/Time
teslim_tarihi=Date/Time
sorumlu_marka = Short Text
sorumlu_ajans=Short Text
personel_id=Number
revize=Short Text
is_durum=Short Text
Temsilci_isverenid=Number
I Solved the problem. I realized the rank of parameters was not true. i change my code like that:
OleDbConnection con = new OleDbConnection(Utility.GetConnection());
con.Open();
OleDbCommand cmd2 = new OleDbCommand("INSERT INTO Temsilci(isin_adi,isin_tanimi,verildigi_tarih,teslim_tarihi,sorumlu_marka,sorumlu_ajans,revize,Temsilci_isverenid) values (#isinadi,#isintanimi,#vertarih,#testarih,#smarka,#sajans,#revize,#temsid)", con);
cmd2.Parameters.Add("isinadi", txtisAdi.Text);
cmd2.Parameters.Add("isintanimi", txtMarkaAdi.Text);
cmd2.Parameters.Add("vertarih", txtverilisTarihi.Text);
cmd2.Parameters.Add("testarih", txtTeslimTarihi.Text);
cmd2.Parameters.Add("smarka", txtMarkaTemsilcisi.Text);
cmd2.Parameters.Add("sajans", txtAjansTemsilcisi.Text);
cmd2.Parameters.Add("revize", txtSorumluKisiler.Text);
cmd2.Parameters.Add("temsid", Session["UserID"]);
cmd2.ExecuteNonQuery();
con.Close();
after that i get error like this :
You cannot add or change a record because a related record is required in table 'Personel'.
And i remove the relationship from 2 tables. And now it works normally.
I think access database have some bugs ,and even if code is correct, errors may accuired.
So i will move my database to SQL from ACCESS i think. Thanks guys.

I want to populate DropDownList2 from the result of DropDownList1 and delete the row in asp.net 2012 using c#

I used the below code. It displays all the fields in the 1st dropdown as required. the second drop down should contain all the values of the fields selected in the 1st dropdown.
SqlCommand com = new SqlCommand("SELECT DISTINCT " + DropDownList3.SelectedItem.Text + " FROM servers", sqlcon);
SqlDataReader dr;
dr = com.ExecuteReader();
DropDownList4.Items.Clear();
while (dr.Read())
{
DropDownList4.Items.Add(new ListItem(dr[0].ToString()));
}
The delete operation should be performed based on the two dropdown values.
SqlCommand delete = new SqlCommand("DELETE FROM servers WHERE '" +DropDownList3.SelectedItem.Text+ "' = '"+ DropDownList4.SelectedItem.Value +"'" , sqlcon);
It is not showing any errors, but it is not giving expected results. Can you please help ?
NEVER use inline queries in code. This may yield SQLInjection attacks. Always use parameterized sql stored procedures.
Try this:
Set both Text and Value in ListItem
while (dr.Read())
{
DropDownList4.Items.Add(new ListItem(dr[0].ToString(),dr[0].ToString()));
}

How to set dropdown list value and item as database table value in edit?

When I click edit button the form filling database values in textbox as well as dropdown list..
Textbox values is set. But I can't set dropdownlist values..
The code is;
SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
string str = "Select * from Master where Id='" + id + "'";
SqlCommand command = new SqlCommand(str, con);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
ddCustomerName.DataValueField = reader["CustomerId"].ToString();
txtPickupLocation.Text = reader["Location"].ToString();
}
con.Close();
you have to make the CustomerId in the list selected,for that you have to write
ddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()).selected=true;
instead of
ddCustomerName.DataValueField = reader["CustomerId"].ToString();
Hey Saranya earlier post is perfect but it gives error if Dropdown values not matched with DB value or if Dropdown havn't value which is return by Db ,So Safer side always checks null value also.
Please Use this code
if (ddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()) != null)
dddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()).selected = true;
use selectedvalue property
while (reader.Read())
{
ddCustomerName.SelectedValue= reader["CustomerId"].ToString();
txtPickupLocation.Text = reader["Location"].ToString();
}

C# Fill combo box from SQL DataTable

DataTable _dt = new DataTable();
using (SqlConnection _cs = new SqlConnection("Data Source=COMNAME; Initial Catalog=DATABASE; Integrated Security=True"))
{
string _query = "SELECT * FROM Doctor";
SqlCommand _cmd = new SqlCommand(_query, _cs);
using (SqlDataAdapter _da = new SqlDataAdapter(_cmd))
{
_da.Fill(_dt);
}
}
cbDoctor.DataSource = _dt;
foreach(DataRow _dr in _dt.Rows)
{
cbDoctor.Items.Add(_dr["name"].ToString());
}
There was an Error...
The result is System.Data.DataRowView instead of data from database..
I'm not yet sure what is the exact error in your code, but if you're ok with not using DataTable, you can do it this way:
using (SqlConnection sqlConnection = new SqlConnection("connstring"))
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM Doctor", sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
cbDoctor.Items.Add(sqlReader["name"].ToString());
}
sqlReader.Close();
}
For more information take a look at SqlDataReader reference on MSDN.
In orer to find the issue in the original code you posted, please provide information in which line you get the exception (or is it an error that prevents application from compiling?) and what is its whole message.
You could also specify DisplayMember property of combobox to any of the column name.
For example if you want to display Name field, you could do
Combobox1.DisplayMember="Name";
I think the problem is that you are trying to insert multiple columns into a comboBox (which can accept only one column). Adjust your SELECT statement so that it combines all of the data you need into one column:
Example:
SELECT Name + ' ' LastName + ' '+ ID AS 'DoctorData' FROM Doctor
By using the + operator you can combine multiple columns from the database, and represent it as a single piece of data. I think that your code should work after that (you can even comment the foreach loop, I think that adding data source to your comboBox will be enough)

Get data from SQL Server database into label

In my ASP.Net webpage, I have a label and need the label's text to be retrieved from my database.
I have no problem writing to my database, but it seems trying to retieve the data again is a mission...
What I need is to get the data from the Price column in my database, from the table Tickets, from the record where the ConcertName data is the same as my webpage's title, or a string associated with my webpage.
I have tried many tutorials already, but all just throw me errors, so I decided to try one last place before I just give in and make my labels static.
In case it helps, I have tried the following:
First Try
Second Try
Third Try
Fourth Try
Hopes you use c#
string MyPageTitle="MyPageTitle"; // your page title here
string myConnectionString = "connectionstring"; //you connectionstring goes here
SqlCommand cmd= new SqlCommand("select Price from Tickets where ConcertName ='" + MyPageTitle.Replace("'","''") + "'" , new SqlConnection(myConnectionString));
cmd.Connection.Open();
labelPrice.Text= cmd.ExecuteScalar().ToString(); // assign to your label
cmd.Connection.Close();
Looks like you want to bind the label to a data source. Here is a great example that works.
Here is an example protecting against SQL Injection and implicity disposes the SqlConnection object with the "using" statement.
string concert = "webpage title or string from webpage";
using(SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["connString"].ConnectionString))
{
string sqlSelect = #"select price
from tickets
where concert_name = #searchString";
using(SqlCommand cmd = new SqlCommand(strSelect, conn))
{
cmd.Parameters.AddWithValue("#searchString", concert);
conn.Open();
priceLabel.Text = cmd.ExecuteScalar().ToString();
}
}
If you're interested in researching ADO .Net a bit more, here is a link to the MSDN documentation for ADO .Net with framework 4.0
http://msdn.microsoft.com/en-us/library/h43ks021(v=vs.100).aspx

Categories