Drop Down List not getting populated - c#

I have a c# code line as,
using (SqlDataSource sqlds = new SqlDataSource(ConnectionString(), SelectCommand()))
{
drop1.DataSource = sqlds;
drop1.DataTextField = "UserName";
drop1.DataBind();
}
now it's not populating my dropdownlist,
<asp:DropDownList id="drop1" runat="server" />
so I want to check if sql is returning data or not
if i put line break, I am not sure how to find out if sql is returning data, I am using using select statement and connection string for gridview and it works but not with drop down list

Be sure you have your sqlquery into select command then you need convert you
sqldatasource select command into dataview.
string query = "select yourfield from yourtable";
using (SqlDataSource sqlds = new SqlDataSource(conn.ConnectionString, query))
{
System.Data.DataView dv = (System.Data.DataView)sqlds.Select(DataSourceSelectArguments.Empty);
if (dv.Count > 0)
{
DropDownList1.DataSource = sqlds;
DropDownList1.DataTextField = "yourfield";
DropDownList1.DataBind();
}
}

You should be able to put a breakpoint on drop1.DataSource = sqlds; and then move your mouse over sqlds and it should show you how many rows are contained in the DataSource.

your way of binding datasource to the dropdown is correct and same thing is working for me.
Possible errors can be
in the connectionString. Verify if it is correct.
in the Select Query. Verify if the SelectCommand() methods returns correct sql query.
use Selected event of the SqlDataSource to verify whether it returned any row i.e
sqlds.Selected += new SqlDataSourceStatusEventHandler(sdl_Selected);
where sql_Selected is:
void sdl_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
var a = e.AffectedRows;
}
as a Side note - make sure your select query doesn't contain any string concatenation prone to sql injection. i.e. SELECT UserName from [TableName] where certainCol ="+ variable.
Don't do it
provide a sql parameter instead, and add the SelectParameters to your SqlDataSource

Related

Drop Down List is not finding correct value

When I connect my dropdownlist (cmbStaff) and then try and apply a selected value to cmbStaff it will always return the very first value within the dropdownlist.
Here is the code I use to bind data to the dropdownlist
if(!IsPostBack)
{
String Sql = #" select * from SupportTeam";
SqlConnection conn = new SqlConnection(Properties.Resources.cString);
SqlDataAdapter DA = new SqlDataAdapter(Sql, Properties.Resources.cString);
DataSet DS = new DataSet();
DA.Fill(DS, "SupportTeam");
cmbStaff.DataValueField = "SupportTeamID";
cmbStaff.DataTextField = "SupportTeamName";
cmbStaff.DataSource = DS;
cmbStaff.DataBind();
cmbStaff.Items.Insert(0, "--Please select a support team--");
}
But in future code when I try and apply a selected value to the drop down it will always select the first index.
For example, if I do this
cmbStaff.SelectedValue = "TEL";
When I debug, it will always return this
cmbStaff.SelectedValue = "--Please select a support team--"
cmbStaff.SelectedIndex = 0;
Why is it doing this.
I have data stored in the table as the combo works it just does not set starting index to the value that I want and that is what I need it to do.
Here is a snippet of the data I have stored in the SupportTeam Table
Sorry if is seem vague, thanks in advance!
That is not how you set a selected value for a drop down list. you use the findbyvalue function and set selected =true
cmbStaff.Items.FindByValue("TEL").Selected = true;
The problem I was having was Sql Related. It keep adding blank spaces onto the end of the value I was entering. I changed
String Sql = #" select * from SupportTeam";
to
String Sql = #" select rtrim(SupportTeamID) as SupportTeamID, rtrim(SupportTeamName) as SupportTeamName from SupportTeam";
It now works. I cannot find the exact reason why this happened. Of course the .Trim() function will also work when declaring Sql variables in c#.

USe Values from Gridview

I am using a web form to pull data from a sql database, populate a datatable and use that datatable to populate a Gridview.
The code for populating the GridView when the search button is pressed
executes a Sql Query then sets the data Source to the datatable (GT1)
GT1.Load(SCDR);
EntryGrid.ShowHeaderWhenEmpty = true;
EntryGrid.DataSource = GT1;
EntryGrid.DataBind();
EntryGrid.EditIndex = 0;
EntryGrid.DataBind();
I was originally going to just use the gridview to populate a series of variables and use those to generate a Sql query, but EntryGrid.Rows[0].Cells[2].Text produces an empty string.
row.Cells[4].Text returns nothing in GridView1_SelectedIndexChanged? talks about using FindControl("control ID") , but I just got more confused looking at this. how do I find the control ID, and what exactly would I need to do to take a value from a specific cell in the gridview to a string variable?
The gridview is populated by the following code
DataTable GT1 = new DataTable();
protected void Button1_Click(object sender, EventArgs e)
{
string SqlQuery1 = sql.Replace("LASTNAME_", LastnameBox.Text);
SqlQuery1 = SqlQuery1.Replace("LAST4_", PAsswordBox.Text);
SqlConnection Conn1 = new SqlConnection(DC1.DbConn);
Conn1.Open();
SqlCommand SearchCommand = new SqlCommand(SqlQuery1, Conn1);
SqlDataReader SCDR = SearchCommand.ExecuteReader();
GT1.Load(SCDR);
EntryGrid.ShowHeaderWhenEmpty = true;
EntryGrid.DataSource = GT1;
EntryGrid.DataBind();
EntryGrid.EditIndex = 0;
EntryGrid.DataBind();
}
The Control ID is the Id you set for your each of your items in the TemplateField. Here is an example of using the FindControl to get the information from a label and storing it in VarFromGrid. The row is grab by RowSelected. Not sure how you are wanting to get the row but that is one way to do it.
aspx code:
<asp:Label ID="LabelGridViewBankName" runat="server" Text="something"></asp:Label>
code behind:
GridViewRow row = GridView1.SelectedRow;
string VarFromGrid = row.Cells[4].FindControl('LabelGridViewBankName').Text;
EDIT:
You can use a GridViewRow to grab the row, then grab the data from it like below. You shouldn't need the find control.
GridViewRow row = (GridViewRow)EntryGrid.SelectedItems[0];
string something = row.Cells[0].Text;
Just remember to make sure the Grid row is not null or you'll get a null exception. And to close your connection string once done. I this still returns an empty string, take a look at your dataTable in debug mode and see how the data is being stored.

Dependant dropdownlist(cascading)

I have an existing dropdownlist that lists names.
I am trying to create another drop down list that contaings all Alphabets
What i am trying to accomplish is:
When a user selects an alphabet from the Alphabet Dropsownlist, the second dropdwonlist will populate all the names that start with the selected Alphabets.
I had this code.
`NamesDropDownList.SelectedValue = (NamesDropDownList.DataValueField).Where(NamesDropDownList.SelectedItem.Value).Contains(AlphabetsDropDownList.SelectedItem.Value);`
but it is giving me an error:
Error Message: string does not contain a definition of Where, and the method overload contains invalid arguments.
Any Help Or approach to this problem.
thanks
There are several things wrong with that one line of code. Let's start with the source of the data. This is not the source of your data:
NamesDropDownList.DataValueField
That's just a string property on a DropDownList. You can't select records from that, you have to select them from the database (or wherever your backing data is). You haven't provided that context, so I'm going to suppose it's some standard LINQ-queryable data source. Let's say, for the sake or example, that it's something like this:
dbContext.Names
That is what you'd attach a "where" clause to in order to select data. So now let's move on to that clause and see what it looks like. For starters, it doesn't look like this:
.Where(NamesDropDownList.SelectedItem.Value).Contains(AlphabetsDropDownList.SelectedItem.Value)
The .Where() method doesn't expect a string, it expects a Func<T, bool> as a predicate. Inside that predicate is where you'd have your .Contains(), which would operate on the string and not on the whole collection. So it might look something like this:
dbContext.Names.Where(n => n.Name.Contains(AlphabetsDropDownList.SelectedItem.Value))
What this line of code essentially does is:
From the Names table in the database, select all records where the Name column contains the given value.
That would give you the filtered set of records from the data source, which could then be used to bind to the next DropDownList.
Look into creating an event handler on the parent DDL
Dynamic DDL Event Handler
DropDownList Change Event
Just have the SelectedIndexChanged() event handler from the alphabet dropdownlist populate the names list:
private DataSet GetNameData()
{
string sql = "select Firstname, Lastname from Names where Firstname like '#Letter%';";
SqlParameter arg = new SqlParamter("#Letter", ddlLetter.SelectedItem.Value));
SqlCommand cmd = new SqlCommand, sql, ConnectionString);
cmd.Paramters.Add(arg);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = cmd;
da.Fill(ds);
return ds;
}
private void ddlLetter_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet Names = GetNameData();
ddlNames.DataSource = Names.Table[0];
ddlNames.DataTextField = "Firstname";
ddlNames.DataValueField = "Id";
ddlNames.DataBind();
ddlNames.Items.Insert(0, new ListItem("Please select a name", 0);
}
Make sure you have the alphabet dropdownlist set with AutoPostBack="true" otherwise it won't work.
Hope this helps!

Execute a SQL SELECT query and display the results in a GridView on button click

Context: I'm designing a simple ASP.NET webpage where I have a search box where the user can enter a User ID (int) and when they click a search button, a GridView control displays the results of a SQL SELECT query that checks if an entry with the specified User ID exists. This functionality all works and I believe is fairly simple.
I've added another button that I would like to execute a different SQL SELECT query that returns all entries in the table.
Here is the first SELECT query, which is the SelectCommand of the SqlDataSource that the GridView uses: SELECT * FROM [tblUser] WHERE [UserID] = #UserID
Here is the new SELECT query that I want to execute when a user clicks the new button: SELECT * FROM tblUser
Question: How can I use the "OnClick" event (in the code behind) to execute this new query and display the results in the same GridView?
What I've Tried: This seems like a pretty logical way of executing the new statement: change the SelectCommand of the SqlDataSource that the GridView control uses, execute that SelectCommand, then display the results of that command in the GridView. Unfortunately it just results in an empty GridView, no column labels or anything.
string selectAll = "SELECT * FROM tblUser"; //new query to execute
string oldSelect = SqlDataSource1.SelectCommand; //stores old query in temp variable
SqlDataSource1.SelectCommand = selectAll; //sets the SelectCommand of the DataSource to the new query
SqlDataSource1.Select(DataSourceSelectArguments.Empty); //executes the SelectCommand
GridView1.DataBind(); //binds the GridView to the DataSource
SqlDataSource1.SelectCommand = oldSelect; //returns the select command to its original value
The problem is that you forgot to assign the DataSource and DataSourceID to the GridView after changing the SelectCommand:
string selectAll = "SELECT * FROM tblUser"; //new query to execute
string oldSelect = SqlDataSource1.SelectCommand; //stores old query in temp variable
SqlDataSource1.SelectCommand = selectAll; //sets the SelectCommand of the DataSource to the new query
SqlDataSource1.Select(DataSourceSelectArguments.Empty); //executes the SelectCommand
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind(); //binds the GridView to the DataSource
SqlDataSource1.SelectCommand = oldSelect;
And to return to your old select, in a different button click event:
SqlDataSource1.Select(DataSourceSelectArguments.Empty); //executes the SelectCommand
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
EDIT
considering you use entity framework,
in codebehind:
Public Shared Function getUsers(optional byval userid as integer = 0) as list(of myusers)
Using db as new your_user_entity
dim users = (from u in db.Users select u)
if userid = 0 then
return users.toList()
else
return users.where(function (x) x.userid = userid).toList()
End If
End Using
End
after this, you can call this function on one button click like:
gridview.datasource = getUsers() ' will give you all users
gridview.databind
on another button:
gridview.datasource = getUsers(10) ' will only give you the user with id=10
girdview.databind
change your logic a little bit. In code behind, create two functions
getSingleUserDetails
getAllUsers
both functions should return List(of Your_user)
then in button click events for both buttons,
e.g. btnGetSingle_Click
gridview.datasource = getSingleUserDetails(10)
gridview.databind
btnGetAllUsers_Click
gridview.datasource = getAllUsers
gridview.databind
Note: I am omitting some facts such as you can use overloaded functions, entity framework etc..
This is what I had to do:
1) Assign the DataSource and DataSourceID of the GridView after changing the SelectCommand.
2) Remove the SelectParameter of the search textbox before executing the new SelectCommand, then add it back before doing the regular search.
Here's my code for my button click event for the "Show All" button:
protected void ShowAllUsers(object sender, EventArgs e)
{
UserIDTextBox.Text = "";
SqlDataSource1.SelectCommand = selectAll;
SqlDataSource1.SelectParameters.Remove(SqlDataSource1.SelectParameters["UserID"]);
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
SqlDataSource1.SelectCommand = selectUser;
}
And then for my regular search button:
if (SqlDataSource1.SelectParameters.Count == 0)
{
SqlDataSource1.SelectParameters.Add("UserID", UserIDTextBox.Text);
}
SqlDataSource1.SelectCommand = selectUser;
selectUser and selectAll are the strings holding the SQL querys.

DropDownList not population from SQL Database

I am missing something. I am trying to populate a drop down list from a table in a SQL database. I have several columns in the table but only want 2, 1 for value and 1 for text based on the value that is entered from a textbox. My test page I just gave the session variable a value from my table. I have test my SQL connection and varified that works. I have tested my select statement in SQL and varified that I received only the data that I want.
Can some one please tell me what I am doing wrong.
the drop down list is a simple asp DDL:
<asp.DropDownList ID="DD1" runat="server"></asp.DropDownList>
The code behind is:
protected void Page_Load(object sender, EventArgs e)
{
string a = Session["Test"] as string;
string IDSel = "SELECT Value, Text FROM DDL1 WHERE Value = '#Value'";
SqlConnection IDcon = new SqlConnection(connection string);
IDcon.Open();
SqlDataAdapter adapter = new SqlDataAdapter(IDSel, IDcon);
adapter.SelectCommand.Parameters.AddWithValue("#Value", a);
DataSet IDds = new DataSet();
adapter.Fill(IDds);
try
{
DD1.DataSource = IDds;
DD1.DataTextField = "Text";
DD1.DataValueField = "Value";
DD1.DataBind();
}
catch
{
Response.Write("No data found");
}
IDcon.Close();
}
My master page has the:
Session["Test"] = //a value from my table
I have added
Response.Write(a);
at different points and I get the table value displayed where I expected it and I never received no data found.
1 example I found had me add
DD1.BindData();
right after the DD1.DataSource line but that caused error messages about my parameter value. I have ran debug and it runs clean.
try this
DD1.DataSource = IDds.Tables[0];
If you put your parameter placeholder between single quotes it will be treated as a string literal, not as a parameter
string IDSel = "SELECT Value, [Text] FROM DDL1 WHERE Value = #Value";
Also to avoid possible confusion with the reserved keyword I think you need to put the word TEXT between square brackets
its an correct way to add sql parameters
adapter.SelectCommand.Parameters.AddWithValue("Value", a);
and
string IDSel = "SELECT Value, Text FROM DDL1 WHERE Value = #Value";

Categories