I am having an issue with the SelectedValue control. I have first created a comboBox, and tied to it is the following method:
private void Form1_Load(object sender, EventArgs e)
{
SqlCeConnection cn = new SqlCeConnection(#"Data Source = \Program Files\ParkSurvey\ParkSurvey.sdf; Persist Security Info = False; Password = *");
cn.Open();
SqlCeCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT Name FROM Cities ORDER BY Name ASC";
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cn.Close();
cboCities.ValueMember = "CityId";
cboCities.DisplayMember = "Name";
cboCities.DataSource = ds.Tables[0];
cboCities.SelectedIndex = -1;
}
Assuming this is the only code I have present in my form, the comboBox (cboCities) populates accordingly. My issue arises when I try to fill a second comboBox (cboParks) with the corresponding parks associated with that city. This method looks as follows:
private void cboCities_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboCities.SelectedIndex > -1)
{
SqlCeConnection cn = new SqlCeConnection(#"Data Source = \Program Files\ParkSurvey\ParkSurvey.sdf; Persist Security Info = False; Password = *");
cn.Open();
SqlCeCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT Name FROM [Parks] WHERE CityId =" + cboCities.SelectedValue + " ORDER BY Name ASC";
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cn.Close();
cboParks.ValueMember = "ParkId";
cboParks.DisplayMember = "Name";
cboParks.DataSource = ds.Tables[0];
cboParks.SelectedIndex = -1;
}
}
When I load up my Mobile Application, the first comboBox does not populate correctly and is in fact displaying data along the lines of: "System32.Data....", and when selecting any of them, I am brought to the runtime error that states “There was an error parsing the query. [Token line number = 1, Token line offset = 52,Token in error = Data]”. I have been lead to believe the issue itself is from the SELECT statement here:
cmd.CommandText = "SELECT Name FROM [Parks] WHERE CityId =" + cboCities.SelectedValue + " ORDER BY Name ASC";
When I change the cboCities.SelectedValue to cboCities.SelectedItem, the comboBox cboParks populates appropriately minus the filtering (it brings back ALL the data). I can also change it to simply CityId (for testing purposes) and the SELECT statement works.
I have also tried to paramertize it as such, but am brought to an entirely different error: "No mapping exists from DbType System.Data.DataRowView to a known SqlCeType."
cmd.CommandText = "SELECT Name FROM [Parks] WHERE CityId = #CityId ORDER BY Name ASC";
cmd.Parameters.AddWithValue("#CityId", cboCities.SelectedValue);
Basically, what is causing SelectedValue NOT to work and bring back the appropriate CityId ValueMember of the first method? I am pulling my hair out trying to figure this out. Also, if anyone has another method of binding selected data to comboBoxes, then please do share! I'm new to the C# world so any help is much appreciated. Thank you.
As from MSDN,
The SelectedValue return the value of the member of the data source specified by the **ValueMember** property.
You specify as ValueMember the field CityID, but in your query this field is not present.
Therefore the SelectedValue returns the result of the ToString() method of the object.
that happens to be a System.Data.DataRowView.
I think you could resolve your problem simply adding that field to your query
So change your code in this way
using(SqlCeConnection cn = new SqlCeConnection(#"Data Source = \Program Files\ParkSurvey\ParkSurvey.sdf; Persist Security Info = False; Password = *"))
{
cn.Open();
SqlCeCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT CityID, Name FROM Cities ORDER BY Name ASC";
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
}
....
then you will be able to use parameters on the second query.
Your Select Statement that fills the Combobox is wrong
cmd.CommandText = "SELECT Name FROM Cities ORDER BY Name ASC";
Should be
cmd.CommandText = "SELECT Name, CityID FROM Cities ORDER BY Name ASC";
Related
I want to display a category (service) based on menu item value, so when the user clicks on music item for example it should fill the repeater from database table (ServiceP) where the name of the service = to the menu item value.
I tried this code, but I get an error
System.Data.SqlClient.SqlException: 'Invalid column name 'music'
This is the code when users clicks a menu item
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\TOSHIBA\Documents\PartyZone.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from ServiceP where
ServiceName = "+e.Item.Value.ToString() ;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
d1.DataSource = dt;
d1.DataBind();
conn.Close();
}
Assuming you actually have:
cmd.CommandText = "select*from ServiceP where ServiceName="+e.Item.Value.ToString() ;
and e.Item.Value is "music", then what you need here is a parameter to hold the value to search for, i.e.
cmd.CommandText = "select*from ServiceP where ServiceName=#value";
cmd.Parameters.AddWithValue("#value", e.Item.Value.ToString());
Note that you can also throw away the cmd.ExecuteNonQuery(); - that does nothing useful here, and means you do the work twice.
I am making a school application about articles publication. In a dropdownList I want to display the value that exists in database as default pre-selected value. DropdownList conatins "emertimi" from table "kategorite". When user selects a value it saves id of "kategoria_id" in table "artikulli". Here is my code behind
if (e.Item.ItemType == ListItemType.EditItem)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection);
string Qry = "select * from kategoria";
string id = Request.QueryString["id"];
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
DataSet ds2 = new DataSet();
DataSet ds3 = new DataSet();
con.Open();
da.Fill(ds);
string kategoria_id = "select kategoria_id from artikulli where id='" + id + "'";
SqlDataAdapter dk = new SqlDataAdapter(kategoria_id, con);
dk.Fill(ds2);
var kategoria_id_result = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
string emertimi = "select emertimi from kategoria where id='" + kategoria_id_result + "'";
SqlDataAdapter de = new SqlDataAdapter(emertimi, con);
de.Fill(ds3);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText(emertimi).Value;
con.Close();
con.Dispose();
ds.Dispose();
ds2.Dispose();
ds3.Dispose();
da.Dispose();
dk.Dispose();
de.Dispose();
}
}
But it's showing this error: Object reference not set to an instance of an object. at this line: drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText(emertimi).Value;
I guess emertimi contains a value that cannot be found in the dropdown list. Therefore, the FindByText will return null and getting the Value will result in this exception.
Test the result before you try to get the Value.
Also, instead of the separate Dispose calls, use using statements. And be aware of the SQL injection risk: use parameters instead.
That's because the item you're looking for has not been found. You should troubleshoot your code and figure out what emertimi is set to at run time.
I want to fetch all rows that related to the query below, my problem that only one row retrived not all rows , iam using asp.net with c# and ado.net and my code logic is
if (!IsPostBack)
{
string username = Session["username"].ToString();
con.Open();
string strqryScript = "select * from dbo.teachers where user_id = '" + username + "'";
SqlCommand cmd = new SqlCommand(strqryScript, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
string name = rdr["teach_id"].ToString();
rdr.Close();
string query = "select * from dbo.teacher_classes where teach_id = '" + name + "' ORDER BY class_id";
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
SqlDataReader rdr2 = cmd2.ExecuteReader();
while (rdr2.Read())
{
classname.Text = rdr2["class_id"].ToString();
}
con.Close();
}
extra note that i can use gridview to bind data but i want to fill my table with custom information from many tables , so i want to use an html table and fill it with my custom data. any help please! and thanks ..
While looping on the second reader, you write the value extracted from the reader on the Text property of the classname label. This will overwrite the previous text and leave you with the name of the last teacher retrieved. You need to add to the previous text or use a List.
classname.Text += rdr2["class_id"].ToString();
Said that, let me point you to a big problem in your code. String concatenation is really bad when you build sql commands. It gives you back syntax errors (if your input text contains single quotes) or Sql Injection as explained here
You should use parameterized queries like this (just for your first command)
string strqryScript = "select * from dbo.teachers where user_id = #id";
SqlCommand cmd = new SqlCommand(strqryScript, con);
cmd.Parameters.AddWitValue("#id", username);
....
This is the issue you need to fix:
classname.Text = rdr2["class_id"].ToString(); <== always setting the same text!!
You need to make sure, you fill a list, a dataset or whatever, when reading the data!
I am trying to select a set of data for a ComboBox based on the selection of the previous ComboBox. I have been lead to believe it is the SELECT statement in the second method, but I cannot figure out why it isn't working. When I run the application I receive this error:
The data type is not valid for the boolean operation. [Data type (if
known) = int,Data type (if known) = nvarchar ].
I have attempted using Parameter.AddWithValue and also setting the value as a string to no avail. Would anyone mind teaching me how to correctly resolve this? Thank you.
private void cboCities_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboCities.SelectedIndex > -1)
{
SqlCeConnection cn = new SqlCeConnection(#"Data Source = \Program Files\ParkSurvey\ParkSurvey.sdf; Persist Security Info = False; Password = *");
cn.Open();
SqlCeCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT Name FROM Parks WHERE CityId ='" + cboCities.SelectedValue + "'ORDER BY Name ASC";
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cn.Close();
cboParks.ValueMember = "ParkId";
cboParks.DisplayMember = "Name";
cboParks.DataSource = ds.Tables[0];
cboParks.SelectedIndex = -1;
}
Have you tried something like the following?
//[...code...]
cmd.CommandText = "SELECT Name FROM Parks WHERE CityId = #CityId ORDER BY Name ASC";
cmd.Parameters.Add("#CityId", System.Data.SqlDbType.Int, 2).Value = Convert.ToInt32(cboCities.SelectedValue);
//[...code...]
Is the CityId in the Parks table is an integer?
You are comparing an int ie CityId to a string '...value in cboCities.SelectedValue ...'
Try casting the City it to and integer :
cmd.CommandText = "SELECT Name FROM Parks WHERE CAST(CityId AS NVARCAR) ='" + cboCities.SelectedValue + "'ORDER BY Name ASC";
Or if you are sure that the in cboCities.SelectedValue is the same as CityId you can also try it without the quotes (an integer to integer comparison)
cmd.CommandText = "SELECT Name FROM Parks WHERE CityId = " + cboCities.SelectedValue + " ORDER BY Name ASC";
(note I've removed the single quotes around cboCities.SelectedValue)
I have folowing code of c# in which I am making connection with access db and and using some conditions.I call a single row from db by using where clause in query.When I Logged into the page it gets data accurately.But after some time when i refresh the page it shows the folowing error
"There is No Row at position 0"
My code is is Bellow
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|OID.mdb;Persist Security Info=False;");
//OleDbConnection con = new OleDbConnection("Data Source=sml; User ID=sml; Password=sml; provider=OraOLEDB.Oracle");
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Select * from EMAILS WHERE EMAIL= '" + GlobalData.Email + "'";
//cmd.CommandText = "Select * from EMAILS";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
String email = ds.Tables[0].Rows[0][1].ToString();
if (email == GlobalData.Email)
{
Label2.Text = GlobalData.Email;
Label1.Text = GlobalData.Name;
Label3.Text = GlobalData.LastName;
Label1.Visible = false;
Label3.Visible = false;
Label4.Text = Label1.Text + ' ' + Label3.Text;
}
}
I am querying data from DB and using where cluse with Global Variable to retrive a single row
Can Any one Please tell me that how can i Remove this issue or can i loop through the DB that evry time when user login it gets data using loop and then follow the condtion
That means your query is not returning anything and therefore when you call this line:
String email = ds.Tables[0].Rows[0][1].ToString();
You get an exception because there's no Row[0]
If you want to avoid that error do something like:
if (ds.Tables[0].Rows.Count>0)
{
String email = ds.Tables[0].Rows[0][1].ToString();
///...
}
Don't do select * ever in your code. Get used to list the exact columns you want to select from the table. For example:
select email_address from Emails where id= 5
Extra comment: Your query above is kind of pointless; it seems that you are trying to select an email address from a table using the same email address in the where clause. Why do you need to select it from the database if you already know the email? Judging by the variable name (GlobalData.Email) it seems that this is a predefined value...