If the Select statement has been specified on the .aspx page, and then later altered in the code-behind, based on some event-driven logic, is there a way to revert the select statement to what is originally on the .aspx page?
The ASP code:
<asp:SqlDataSource ID="ds_Users" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
SelectCommand="SELECT * FROM [Users]" >
</asp:SqlDataSource>
In the codebehind:
ds_Users.SelectStatement += " WHERE [UserType] LIKE '" + LocalVariable + "'";
Let's assume the above event was bound to a filter combobox that has the UserTypes as items.
If there's a "View All" option included in that list, how would I revert the SelectStatement to the original query without storing the Select statement (SELECT * FROM [Users]) as another string in the code-behind. Is that even possible?
You have to always fix the SQL Select Command, on every page load, or on post back. You do bind ones, and then again only if you click on a button that change the SQL command.
Here is an example, please note gvMyLista is the GridView that use the data.
protected void Page_Load(object sender, EventArgs e)
{
FixTheSelectCommand();
}
void FixTheSelectCommand()
{
// this is an example - make your test here to know if there is a valid variable
if(LocalVariable != null)
ds_Users.SelectCommand = "SELECT * FROM [Users] WHERE [UserType] LIKE '" + LocalVariable + "'";
else
ds_Users.SelectCommand = "SELECT * FROM [Users]";
if (!IsPostBack)
gvMyLista.DataBind();
}
// when a search button clicked that change the search text
protected void btnSearchFor_Click(object sender, System.EventArgs e)
{
gvMyLista.DataBind();
}
Related
When I choose any option from the dropdown list and then insert it into the database, the first option is chosen automatically, even if I choose the second or third option; only the first option is inserted each time.
Order.aspx.cs
protected void selectList()
{
conn = new SqlConnection(connstr);
conn.Open();
sql = "SELECT * FROM Product";
SqlCommand comm = new SqlCommand(sql, conn);
adap = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
adap.Fill(ds);
ProductID.DataTextField = ds.Tables[0].Columns["Name"].ToString();
ProductID.DataValueField = ds.Tables[0].Columns["Id"].ToString();
ProductID.DataSource = ds.Tables[0];
ProductID.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
bindGrid();
selectList();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
selectList();
sql = "INSERT INTO [Order] (CustomerID,ProductID ,EmployeeID,Quantity,Date) VALUES ('" + CustomerID.Text + "','" + ProductID.SelectedValue + "','" + EmployeeID.Text + "','" + Quantity.Text + "','" + Date.Text + "')";
conn = new SqlConnection(connstr);
conn.Open();
comm = new SqlCommand(sql, conn);
comm.ExecuteNonQuery();
conn.Close();
bindGrid();
ScriptManager.RegisterStartupScript(Page, Page.GetType(),
"myPrompt", "alert('Successfully Updated!');", true);
}
Order.aspx
Product ID:
<asp:DropDownList ID="ProductID" runat="server" CssClass="form-control" ></asp:DropDownList>
Actually, the mistake here is the page load. In 99% of ALL pages, you only want to bind and load up on the first page load. And most if not all asp controls will automatic persist for you. So, your big mistake is this:
protected void Page_Load(object sender, EventArgs e)
{
bindGrid();
selectList();
}
The above has to become this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGrid();
selectList();
}
}
In fact, you really can't build a functional web form page unless you follow the above rule. Remember, any button, any post-back, and the page load event will run again.
So yes, page load is the right place, but you in near 99% of cases need to wrap that code in the all important isPostBack = false code stub.
Once you do above, then your whole page will operate quite nice, quite normal, and in near all cases, you find the controls correct persist their values and settings.
So, no, page load is NOT too soon, and page load is VERY much the correct event and place to load up the data bound controls - but, you only want to do this on the really first page load.
In fact, there is probably 1 question near per day on SO, and their woes and problems can be fixed by following the above simple rule. Failure to note the above isPostBack? You can't really even build a working asp.net page.
Page_Load() is too late to bind your list.
Remember, when using web forms, you start from scratch and have to recreate all of your data items on every single request... even simple button click events*. This is why you call bindGrid() in the Page_Load() method. However, part of this process also involves restoring ViewState, so the button click will know what item was selected. The problem is this ViewState data is restored before the Page_Load() method is called. Therefore the grid is still empty, and the SelectedValue information you need to get from ViewState cannot be set correctly.
You can fix this by moving the code that binds your grid data up to the Init or Pre_Init events.
While I'm here, I need to reiterate my comment about SQL Injection. This is a really big deal... the kind of thing that's too important to do wrong even with learning and proof-of-concept projects. I suggest using Google to learn more about using parameterized queries with C#.
Additionally, it's rare to insert selections directly into an Orders table. Often there's a separate "ShoppingCart" table, using a Session Key for the table's primary key, where the user can build up the cart before completing the order and creating the final Order and OrderLines or OrderDetail records.
* For this reason, it's often worthwhile in web forms to do more of this work on the client browser, in javascript.
So I want to have a DDL (SELECT name FROM sys.databases (nolock)) that returns a value once selected (displayed in gridview possibly).
The problem that I have is that the query needs to make a connection to different databases depending on what the user selects from the DDL and return a value that is displayed in gridview. I want something like the below query:
How could I accomplish this?
use ([name]=#name) select sum(t.table1.column1) as Total from database inner join database2 on db1.table1.id= ([name]=#name).table2.id where([appname]=#appname) and Date <= GetDate()AND YEAR(Date) = year(GetDate())
I got this so far (not sure if this is the best method.) This is my code behind, how do I display the result using gridview that is dependent on DDL?
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
{
if (DropDownList2.SelectedValue == "test1")
{
SqlDataSource3.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["test1ConnectionString"].ConnectionString;
{
SqlDataSource3.SelectCommandType = SqlDataSourceCommandType.Text;
SqlDataSource3.SelectCommand = "select top 10 * from table1 (nolock)";
}
}
else if (DropDownList2.SelectedValue == "test2")
{
SqlDataSource4.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["test2ConnectionString"].ConnectionString;
{
SqlDataSource4.SelectCommandType = SqlDataSourceCommandType.Text;
SqlDataSource4.SelectCommand = "select top 1 * from table1 (nolock)";
}
}
And below is my aspx code for the DDL.
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
<asp:ListItem>test1</asp:ListItem>
<asp:ListItem>test2</asp:ListItem>
</asp:DropDownList>
From what I understand you want to run different SQL when a user selects an item from the DropDownList. Anyway, you should put your code in the SelectedIndexChanged event of the control. As an example, your markup might look something like this:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
And in your code-behind:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// call your sql
}
Edit
I've included a links to get your started. They show some code with the SelectedIndexChanged event.
http://www.devasp.net/net/articles/display/1294.html
http://www.c-sharpcorner.com/UploadFile/092589/working-with-dropdownlist-slectedindexchanged-event/
I have a drop-down list and uses the SQL data source for it where I am retrieving the product names from SQL server. Now, I want to add "Please Select a product" Option to the drop-down list.
As far as my knowledge, I add options to drop-down list by using
<asp:ListItem Selected ="true" Value = "1">1</asp:ListItem>
Since, I am not adding the values but retrieving the values from DB, how to achieve this Option additionally and add to it as first position to my drop-down list?
I tried the below code, but not able to do get at first position.Also, each time I am getting extra "please select" option whenever I am selecting other values.
protected void NameDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
NameDropDownList.Items.Insert(0, new ListItem("Please Select a product", "Please Select a product");
SqlCommand cmd = new SqlCommand("SELECT ProductID, Price, Description, Rating FROM Product_Info Where Name = '" + NameDropDownList.Text + "'", conn);
SqlDataReader myReader;
conn.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read()) {
//Logic
}
conn.Close();
myReader.Close();
Here is my code behind where I bind the data:
<tr>
<td class="style2">Name</td>
<td>
<asp:DropDownList ID="NameDropDownList" runat="server" Height="16px"
Width="130px" AutoPostBack="True" DataSourceID="NameSqlDataSource"
DataTextField="Name" DataValueField="Name"
onselectedindexchanged="NameDropDownList_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="NameSqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ProductsConnectionString %>"
SelectCommand="SELECT [Name] FROM [Product_Info]"></asp:SqlDataSource>
</td>
</tr>
I also enables the Auto post back to true.Thanks in advance
Thanks for your responses. I figured out the actual problem and able to done it in simple step.
First, I make the AppendDataBoundItems behavior of my drop-down list To TRUE and kept the following code and it works perfectly.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
NameDropDownList.Items.Insert(0, new ListItem("Please Select a Product", "Please Select a Product"));
}
}
Move this line NameDropDownList.Items.Insert(0, new ListItem("Please Select a product", "Please Select a product");
t osomewhere after you bind your data, what is happening is that you insert this, then you bind over the top of it.
The problem here is that you're using asp:SqlDataSource. You need to query and bind your data from the code because you want to manipulate it.
Here is the sample logic.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// 1- Query into a list
// 2- Add your custom item at the 1st position
// 3- Set the DataSource of your list
// 4- Make sure you bind your fields (text and value)
}
}
I'll let you try the different steps above, but let me know if you have any trouble.
I have a follow dropdown list in my aspx page:
<asp:DropDownList ID="OrderPeriodStatus" runat="server" AutoPostBack="true"
CssClass="ddlb" Width="100px" Height="30px" DataSourceID="SqlDataSource5"
DataTextField="OrderPeriod" DataValueField="OrderPeriodID" onselectedindexchanged="OrderPeriodStatus_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:ProdDB %> # blah blah query
</asp:SqlDataSource>
I tried to access the value of selected value in C# by following code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ProcessEligibleScenarios();
LoadOptions();
ddlbPeriod.DataBind();
GridView1.DataBind();
gvActiveLogs.DataBind();
}
}
protected void OrderPeriodStatus_SelectedIndexChanged(object sender, EventArgs e)
{
if (OrderPeriodStatus.SelectedValue != null)
{
SqlConnection myConn = default(SqlConnection);
SqlCommand myComm = default(SqlCommand);
myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["ProdDB"].ConnectionString);
myConn.Open();
myComm = new SqlCommand("SELECT OrderPeriodDate, OrderPeriodStatus, Notes FROM OrderPeriod WHERE OrderPeriod ='" + OrderPeriodStatus.SelectedValue + "'");
try
{
myComm.Connection = myConn;
SqlDataReader Dr = myComm.ExecuteReader();
while (Dr.Read())
{
System.Diagnostics.Debug.Write("While reading the data");
TextBox1.Text = Dr["OrderPeriodDate"].ToString();
TextBox2.Text = Dr["OrderPeriodStatus"].ToString();
NotesArea.Value = (string)Dr["Notes"];
System.Diagnostics.Debug.WriteLine(OrderPeriodStatus.SelectedValue);
}
Dr.Close();
myConn.Close();
}
catch (SqlException sqx)
{
}
GridView1.DataBind();
}
else { }
}
But when i print the value. It shows the selected Index not the value. Why?
You have mismatch error on sqdatasource, replace with SqlDataSource4
DataSourceID="SqlDataSource5" <---
<asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:ProdDB %> # blah blah query
</asp:SqlDataSource>
You can try get the value from Request.Form object and to get the text use ddl.Items.FindByValue method
var value = Request.Form[DropDownListnew.UniqeID];
var text = DropDownListnew.Items.FindByValue(value);
If you set AutoPostback property on the dropdownlist to true, and ViewStateMode to inherit, you should get value you selected. I tried it on my side, and it worked. Since you already have SqlDataSource, and the DataSourceId of the dropdownlist is set to the SqlDataSource, it should be populated automatically.
---edit
Sorry, I think I might have misread your question. If you instead use
DropDownListnew.SelectedItem.Text
you should get the text value you want.
-- another edit:
#Amit, you will get index from SelectedValue, because in your dropdownlist code, you have set
DataValueField="OrderPeriodID"
which is basically your primary key or index. To get the text value instead of index you have to use
SelectedItem.Text
Also in your query:
myComm = new SqlCommand("SELECT OrderPeriodDate, OrderPeriodStatus, Notes FROM OrderPeriod WHERE OrderPeriod ='" + OrderPeriodStatus.SelectedValue + "'");
I think you should be using
WHERE OrderPeriodID ='" + OrderPeriodStatus.SelectedValue + "'");
You are missing the ID bit after OrderPeriod.
i have tried to to load the data to text box, while selecting the drop down list, i was created a class for retrieval and called it in drop down list selected index changed. But i cant get the answer what i want. If i have called the class in Button click event it has worked properly. So please correct me. What i made a mistake. This is what my code:
public void so()
{
con.Open();
string s2;
s2 = "select Source from tbl_component where Componetcode='" + Mcodeddl.SelectedItem.Text + "'";
SqlCommand c2 = new SqlCommand(s2, con);
SqlDataReader d2;
d2 = c2.ExecuteReader();
while (d2.Read())
{
TextBox1.Text = d2["Source"].ToString().Trim();
}
d2.Close();
con.Close();
}
//i have called the so class here
protected void Mcodeddl_SelectedIndexChanged(object sender, EventArgs e)
{
so();
}
You should set a breakpoint inside your Mcodeddl_SelectedIndexChanged method to see if the event is triggered, also make sure include AutoPostBack="true" in your dropdownlist definition
Make sure you have specified OnSelectedIndexChanged event for the drop down in aspx page
<asp:DropDownList ID="Mcodeddl" runat="server"
OnSelectedIndexChanged= "Mcodeddl_SelectedIndexChanged">
</asp:DropDownList>
Also use parameterized SQL queries.
PS. Your SO(); is a method not a class.
i have got the answer. And i gave the detail what exactly i have did.
"Set AutoPostBack=True"