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";
Related
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#.
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.
I have searched for most of the day and I believe I may just be not able to explain myself to a search engine. Please forgive me on this.
I have one drop down list I use to get the column names with the code below.
MySQLDataSource.ConnectionString = matt.GetConnectionString();
MySQLDataSource.SelectCommand = "SELECT name FROM sys.syscolumns WHERE (id =
(SELECT id FROM sys.sysobjects WHERE (name = 'tbl_EquipmentStock')))";
DropDownList1.DataValueField = "name";
DropDownList1.DataTextField = "name";
Now, the intention of my work is to use the selected item from this to create the sqldatasource of the next drop down.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
funtions matt = new funtions(); // funtions is the class that contains my connection string.
string frank = DropDownList1.SelectedValue;
a_c_instruction.Text = " Data filtered on: ";
selectedItem.Text = frank;
string sql = "SELECT " + frank + " FROM tbl_EquipmentStock";
AnotherSqlDataSource.ConnectionString = matt.GetConnectionString();
AnotherSqlDataSource.SelectCommand = sql;
DropDownList2.DataValueField = frank;
DropDownList2.DataTextField = frank;
DropDownList2.Visible = true;
}
However, when I attempt to get this to work, the DropDownList2 doesn't populate. What could i be missing? Thank you for looking at my problem.
I tested your code and it works on my machine. I'm guessing that, in order for this to happen right after the column is selected, you need to make sure that the AutoPostBack option on DropDownList1 is set to true.
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
I am new to the wonderful world of dropdownlists and I know this is going to be difficult for me to explain but I will try the best I can.
Here is my data:
**Type** **ID** **Status**
Letter 1 A
Letter 2 B
Letter 3 C
Letter 4 D
Letter 5 E
From my query result I return the ID of "3" and my Drop Down List displays a "C". I have accomplished this piece already :). My question is, how can I populate the dropdownlist with the Statuses? My DDL will display a "C" and when it the arrow is clicked, the rest of the Status values will be displayed.
Is this something that can be done with the sql query? Do I have to create a separate method? If someone could point me in the right direction or provide some helpful code that would be awesome! Here is my code:
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Status FROM dbo.database WHERE ID = #ID AND Type = 'Letter'", mySqlConnection1);
adapter.SelectCommand.Parameters.Add("#ID", SqlDbType.Char).Value = lblID.Text;
adapter.Fill(test);
ddlStatus.DataSource = test;
ddlStatus.DataTextField = "Status";
ddlStatus.DataValueField = Status";
ddlStatus.DataBind();
I think this is what you are looking for:
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT ID, Status FROM dbo.database WHERE Type = 'Letter'",
mySqlConnection1);
adapter.Fill(test);
ddlStatus.DataSource = test;
ddlStatus.DataTextField = "Status";
ddlStatus.DataValueField = "ID";
ddlStatus.DataBind();
ddlStatus.SelectedValue = lblID.Text;
First, fill the DropDownList with the values you need, then set the SelectedValue to have that value automatically displayed. From what I understand, you want the Status to be displayed to the user, but the actual selected value should be the ID.
Depending on your usage of ViewState, you may only need to load the DropDownList once (when the page is first loaded) and then simply set the SelectedValue after that. (You'd need to reload the list on a second page load. Use the IsPostBack value to determine whether or not to reload). There is, however, very little harm in reloading each time, other than a fraction of a second being added to your page load time.
I think what you are looking for is SelectedValue
ddlStatus.DataSource = test;
ddlStatus.DataTextField = "Status";
ddlStatus.DataValueField = "ID";
ddlStatus.DataBind();
//Add this line
string defaultValue = "3";
ddlStatus.SelectedValue = defaultValue; //C has ID of 3