Binding DropDownList using code behind in asp.net - c#

The data binding works only when the page loads first time but it does not work otherwise. Somewhere in my page, i update and insert some new "Names" and i would like to show the newly added Names to be shown in the dropdownlist. But if i reload the page then the newly added Name will appear in the dropdownlist. How can i refresh the items in the dropdown? i thought my code should work. Pls help. thanks
private void RefreshDropDown()
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlConnection con2 = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd1 = new SqlCommand("SELECT DISTINCT [Name] FROM [Main] order by Name asc");
cmd1.Connection = con2;
con2.Open();
DropDownList1.DataSource = cmd1.ExecuteReader();
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Name";
DropDownList1.DataBind();
con2.Close();
}

I assume that you have some kind of button to do insert of new names.
So on click of this button add call for RefreshDropDown() after you done inserting /updating your new names.
That should do the trick.

Related

Getting empty result in output when using Select statement in Grid-View

Here what I have done
I make a GridView and choose the data key name as id and in the basis of id I want to show the DetailsView. Here the CS code
using (SqlConnection con1 = new SqlConnection("Data Source= IA; initial catalog =aip; integrated Security=true;"))
{
con1.Open();
SqlCommand cmd = new SqlCommand("select * from Pm where user_id='" +(String)Session["uid"]+ "'", con1);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con1.Close();
}
Then I make DetailsView method on SelectedIndexChanged:
But it is showing empty DetailsView in output on selecting 'Select' option
here is the code image
enter image description here
You have used the DataSet not DataTable. So you could either do this:
da.Fill(ds,"tbl");
GridView1.DataSource = ds.Tables[0];
Or use a DataTable instead:
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
Also you should always use parameterized queries to avoid SQL Injection. Something like this:
SqlCommand cmd = new SqlCommand("select * from Pm where user_id=#userId", con1);
cmd.Parameters.AddWithValue("#userId", (String)Session["uid"]);
Also have a look at this: Can we stop using AddWithValue() already?
you need to set DataTable instead of DataSet
GridView1.DataSource = ds.Tables["Pm"];
#PIYUSH Itspk please check query and replace
SqlCommand cmd = new SqlCommand("select * from Pm where user_id=" +Session["uid"].tostring()+ ", con1);
i think its help you if any other query please notify me

asp.net dropdown list default value that does not exist in sql table

hi this is my first question on this website
I have a web form with a drop down list, which is being populated from my database which is sql-server 2012.
my table has values like genderID and genderName and it populates the drop down list but I also want to show the default value when the page load event fire "Select gender".
I can add this value in the database to be shown in drop down but this is not the perfect solution as this would mean I have entered a data in sql server which is not a valid data. how can I show this default value in the drop down list which doesnt really exist in the sql server table.
my code behind:
using(SqlConnection con = new SqlConnection(cs))
{
using(SqlCommand cmd = new SqlCommand("select * from dbo.Gender", con))
{
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "GenderName";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
}
}
When the page loads it should show "Select Gender" in the drop down list.
You dont have to add an entry in database to show that default value in your drop down list. You can simply initialize an ListItem object and insert it to the drop down list at index 0.
Remember your drop down list is a collection of ListItem objects, so initialize an object of ListItem type and add it to the drop down list.
Something like ......
using(SqlConnection con = new SqlConnection(cs))
{
using(SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Gender", con))
{
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "GenderName";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
ListItem li = new ListItem("Select Gender", "-1");
DropDownList1.Items.Insert(0, li);
}
}
After data-binding to the dropdownlist, do this:
DropDownList1.Items.Insert(0, new ListItem("Select gender","")
Another option is to add the item using a UNION ALL in your select statement.
Here is the example:
using(SqlConnection con = new SqlConnection(cs))
{
using(SqlCommand cmd = new SqlCommand("select 'Select Gender' genderName, 0 genderID UNION ALL select genderName, genderId from Gender", con))
{
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "genderName";
DropDownList1.DataValueField = "genderID";
DropDownList1.DataBind();
}
}
Something like this would work after you bind:
DropDownList1.Items.Insert(0, new ListItem("Select Gender","-1")

Click Button - No Action

I am trying to retrieve information from database. User enters id of the person he is looking for to ID textbox, than press display button. The grid view should show the result. But when button is pressed, nothing happens. Could anyone help or tell me what I should check?
Code for button:
protected void btnDisplay_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source="Name";Initial Catalog="Name";Integrated Security=True");
SqlCommand cmd = new SqlCommand("displayData", conn);
conn.Open();
cmd.Parameters.Add("#ID", System.Data.SqlDbType.Int).Value = Convert.ToInt32(txtID.Text);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader rd = cmd.ExecuteReader();
grvResults.DataSource = rd;
grvResults.DataBind();
}
Here is stored procedure:
USE ["Name"]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[displayData] (#ID int)
as
begin
SELECT * FROM Customers WHERE ID = #ID
end
Here is display data method:
public List<Customer> displayData()
{
List<Customer> lst = new List<Customer>();
SqlConnection conn = new SqlConnection("Data Source="Name";Initial Catalog="Name";Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * From Customers", conn);
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
lst.Add(new Customer()
{
ID = rd.GetInt32(0),
FName = rd.GetString(1),
LName = rd.GetString(2)
});
}
return lst;
}
aspx for button:
<asp:Button ID="btnDisplay" runat="server" Text="Display" OnClick="btnDisplay_Click" />
have you tried to put a breakpoint in button click. Is it hitting breakpoint. If not then I will say remove
OnClick="btnDisplay_Click"
from your aspx page. And then add default click event from .cs page by selecting control and it events. Them try to debug line by line.
Give the following code a try in your codebehind. It should bind properly and fill a gridview. If it works, add more code from there. If it doesn't work, look at things like your connection string. Let me know.
SqlConnection conn = new SqlConnection("Data Source="?";Initial Catalog="?";Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers WHERE ID = #ID", conn);
cmd.Parameters.Add("#ID", System.Data.SqlDbType.Int).Value = Convert.ToInt32(txtID.Text);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
conn.Close();
grvResults.DataSource = dt;
grvResults.DataBind();
I think you are complicating yourself too much
First do this:
That should make it work. You already have a stored procedure which makes it easier. (Sorry for the pictures, I wanted to make sure you understood this)

how to execute sql select statement in c#

i have a little problem here:
i have a combobox that gets its values from column in database and i use it to enter data back to another palce in database
like
comboBox2.DataSource = ds1.Tables[0];
comboBox2.DisplayMember = "DoctorName";
comboBox2.ValueMember = "DoctorCode";
comboBox2.BindingContext = this.BindingContext;
this fill the combobox with the name of doctors and the value will be the code of doctor
then
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\users\administrator\documents\visual studio 2010\Projects\Clinic\Clinic\Clinc.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
con.Open();
SqlCommand cmd1 = new SqlCommand("SELECT Doctors.DoctorCode, Doctors.DoctorName, SessionReservations.SessionCode, SessionReservations.PatientCode, SessionReservations.ExaminationCode, SessionReservations.DoctorCode AS Expr1, SessionReservations.SessionMonth, SessionReservations.SessionYear FROM Doctors INNER JOIN SessionReservations ON Doctors.DoctorCode = SessionReservations.DoctorCode WHERE (Doctors.DoctorCode = #DoctorCode) AND (SessionReservations.SessionMonth = #month) AND (SessionReservations.SessionYear = #year)", con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd1);
DataSet ds2 = new DataSet();
try
{
da2.InsertCommand.Parameters.Add("#DoctorCode", SqlDbType.Int).Value = Convert.ToInt32(comboBox2.SelectedValue);
da2.InsertCommand.Parameters.Add("#month", SqlDbType.Int).Value = comboBox1.SelectedValue;
da2.InsertCommand.Parameters.Add("#year", SqlDbType.Int).Value = textBox2.Text;
da2.Fill(ds2);
cmd1.ExecuteReader();
con.Close();
}
this code is for selecting specific rows and the select statment is working right in sql manager
but while running it gives error that
"System.NullReferenceException: Object reference not set to an
instance of an object. at
Clinic.DoctorMoneyCall.button1_Click(Object sender, EventArgs e) in
C:\Users\Administrator\documents\visual studio
2010\Projects\Clinic\Clinic\DoctorMoneyCall.cs:line 45"
i just don't understand what's going wrong
It seems like you are trying to run a select command butt you are adding your parameters to the insert command.
da2.SelectCommand.Parameters.Add("#DoctorCode", SqlDbType.Int).Value = Convert.ToInt32(comboBox2.SelectedValue);
da2.SelectCommand.Parameters.Add("#month", SqlDbType.Int).Value = comboBox1.SelectedValue;
da2.SelectCommand.Parameters.Add("#year", SqlDbType.Int).Value = textBox2.Text;
The error message means that one of the objects you used was null. Is the con object correctly initialized?
It seems like you're passing a variable that is null in line 45 of that document. Make sure all values are non-null.

What would cause the SelectedValue control not to work?

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";

Categories