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.
Related
I am trying to delete a record in my database table. I am trying to delete it on the basis of a selected name in the dropdown list. When I debug my code there is not any record available in dataset and an exception "invalid column name" occurs, whereas if I run the same query in SQL Server, everything seems to be fine.
This is my code:
protected void SubCategory_Delete_Click(object sender, EventArgs e)
{
try
{
var conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\template_castle.mdf;Integrated Security=True");
var adpt = new SqlDataAdapter("Select * from tc_prod_subcategory where subcategory_name = ' ' "+ DropDownList2.SelectedItem.Value, conn);
var ds = new DataSet();
adpt.Fill(ds, "tc_prod_subcategory");
foreach (DataRow dr in ds.Tables["tc_prod_subcategory"].Rows)
{
dr.Delete();
}
SqlCommandBuilder build = new SqlCommandBuilder(adpt);
adpt.Update(ds, "tc_prod_subcategory");
Updatesubcategorygrid();
updatedelete_dropdown();
Lblsub_catdelete.Text = "Deleted Successfully";
}
catch(Exception ex)
{
Lblsub_catdelete.Text = ex.Message;
}
}
And this is the same query when I run it in SQL Server 2014; everything runs fine:
Select *
from tc_prod_subcategory
Where subcategory_name= 'Favicon'
The error is caused by the incorrect position of the apostophes in the where clause. It should be like:
"Select * from tc_prod_subcategory where subcategory_name = '" + DropDownList2.SelectedItem.Value + "'"
but that code is vulnerable to a SQL injection,so you should use parameters instead of concatenating strings.
var conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\template_castle.mdf;Integrated Security=True");
var adpt = new SqlDataAdapter("Select * from tc_prod_subcategory where subcategory_name = #subcategory_name", conn);
var ds = new DataSet();
adpt.SelectCommand.Parameters.AddWithValue("#subcategory_name", DropDownList2.SelectedItem.Value);
If you use c# version >= 6.0
you can use interpolation to concat strings in very handy and less error-prone way.
var adpt = new SqlDataAdapter($"Select * from tc_prod_subcategory where subcategory_name = '{DropDownList2.SelectedItem.Value}'", conn);
I wanted to update a record to the database but it just keep reverting to its original value.
Below is my code. No error was display to me either.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CandidateConnectionString"].ConnectionString);
conn.Open();
string updateData = "UPDATE Resume SET [Work_Experience] = #work_exp, [Educational_Level] = #edu_level, [Field_Of_Study] = #field_study, [University_Name] = #uni_name, [University_Location] = #uni_locate, [Graduation_Year] = #gra_year WHERE Cand_ID = (SELECT Cand_ID FROM Candidate WHERE Cand_Username = '"+ usernamelbl.Text +"')";
SqlCommand cmd = new SqlCommand(updateData, conn);
cmd.Parameters.AddWithValue("#work_exp", Work_Exp.Text);
cmd.Parameters.AddWithValue("#edu_level", Edu_Level.SelectedItem.Text);
cmd.Parameters.AddWithValue("#field_study", Field_Study.SelectedItem.Text);
cmd.Parameters.AddWithValue("#uni_name", Uni_Name.Text);
cmd.Parameters.AddWithValue("#uni_locate", Uni_Locate.Text);
cmd.Parameters.AddWithValue("#gra_year", Year.Text);
cmd.ExecuteNonQuery();
conn.Close();
Any Problem with the code?
I just found out a stupid mistake..
On the page_Load event, I have a line of code which is fetching value from the database
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CandidateConnectionString"].ConnectionString);
conn.Open();
string getdata = "SELECT * FROM Resume WHERE Cand_ID = (SELECT Cand_ID FROM Candidate WHERE Cand_Username = '" + usernamelbl.Text + "')";
SqlCommand com = new SqlCommand(getdata, conn);
SqlDataAdapter sda = new SqlDataAdapter(com);
DataSet ds = new DataSet();
sda.Fill(ds, "Resume");
Work_Exp.Text = ds.Tables["Resume"].Rows[0]["Work_Experience"].ToString();
Edu_Level.Text = ds.Tables["Resume"].Rows[0]["Educational_Level"].ToString();
Field_Study.Text = ds.Tables["Resume"].Rows[0]["Field_Of_Study"].ToString();
Uni_Name.Text = ds.Tables["Resume"].Rows[0]["University_Name"].ToString();
Uni_Locate.Text = ds.Tables["Resume"].Rows[0]["University_Location"].ToString();
Year.Text = ds.Tables["Resume"].Rows[0]["Graduation_Year"].ToString();
conn.Close();
But I didn't include it under if(!IsPostBack) and that's the reason whenever I submit, it overwrites my current value and revert it back to the original state. Thanks to you guys who trying to help me sort out and teaches me about new stuff. :)
I have dropdownlist that i have to bind from back end. I am using DataSet to bind the Data but need concatenate two column data in datatextfield of Dropdownlist.
Here is my Code.
string sqlGetClass = "select * from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "brachName"+"-"+"classYear";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
if I use a single column the dropdownlist is binding fine but when concatenate them it is giving error
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'brachName-classYear'.
whene binding the Data.
Code running fine is:
string sqlGetClass = "select * from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "brachName";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
But i need to concatenate branchName and class Like M.Sc-1st Year.
Please Help. Thanks in advance.
Your best option is to specify new column in your query, and then use it as a text field:
string sqlGetClass = "select [pk_classID], [brachName] + '-' + [classYear] as [classText] from tbl_studentClass";
...
ddlClass.DataTextField = "classText";
I have 4 list boxes and I have a DB as EMP with table tab1 and columns Name,EmpId, Salary ...
So I want to display salary in one of the list boxes. How do I do it???
SqlConnection con = new SqlConnection(connec);
string insert_query = "select Salary from tab1";
con.Open();
try
{
SqlCommand cmd = new SqlCommand(insert_query, con);
int exe = cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ListBox3.DataSource = ds;
ListBox3.DataBind();
}
Is this the way? I have some problems like the items are not been displayed in the list boxes.
ListBox3.DataSource = ds;
ListBox3.DataTextField = "Salary";
ListBox3.DataValueField = "EmpID";
ListBox3.DataBind();
you need to specify this before.
your code is right but u need to include some thing like this before binding..
Listbox3.Datasource=ds;
Listbox.DataTextField="Salary"
Listbox.DataValueField="EmpId"
Listbox3.Databind();
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";