In DropDown Selected_Indexchanged event SelectedValue is always getting reset in First Value - asp.net

I have DropdownList which I populate at the time of Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "select distinct sname from contacts where sname is not null";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
DropDownList2.DataSource = table;
DropDownList2.DataValueField = "sname";
DropDownList2.DataTextField = "sname";
DropDownList2.DataBind();
}
}
Now I am trying to populate a GridView when the DropDownList's Item changes
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string val = DropDownList2.SelectedValue;
string sqlQuery = "SELECT distinct DUTY_DATE FROM DUTY_ROTA,DUTY_TYPES,CONTACTS WHERE DUTY_DATE between SYSDATE and SYSDATE+30 AND DUTY_ROTA.DUTY_TYPE = DUTY_TYPES.DUTY_TYPE AND SNAME IS NOT NULL and contacts.sname = '" + val + "' ORDER BY DUTY_DATE";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
I have enabled the AutoPostBack. Now when I am changing a DropDownList item to a different one the Page is loading but always retaining the first value. I tried to debug , I found that
string val = DropDownList2.SelectedValue;
the val variable is always the first value that is returned by the Query. Can anybody please tell me how could I get rid of this. I want to populate the GridView whenever I am selecting any item in the dropdown.

Hi i think that dropdownlist charge again when you select other item. Put a Break Point in Page Load and look if your dropdownlist charge again i don't see other reason. Good Luck

Your Drop downlist should look like as following :
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
Make sure AutoPostBack is Set to TRUE.
One more thing you can try is to select the item when the index is greater than -1.
if(DropDownList2.SelectedIndex != -1)
{
string val = DropDownList2.SelectedItem.Value;
// enter code here
}

Related

Asp.net gridview update with a dropdownlist from the database

this is the error am getting: EQMT' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value'
I am trying to update the data on the gridview with a dropdownlist below is the code.
protected void GridviewRecord_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int RECORD_ID = Convert.ToInt32(GridviewRecord.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)GridviewRecord.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
DropDownList EQMT = (row.FindControl("EQMT") as DropDownList);
GridviewRecord.EditIndex = -1;
using (SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
{ //SqlConnection con = new SqlConnection("ConnectionString");
SqlCommand cmd = new SqlCommand("spEnginehours_Update", con);
try
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
}
catch
{
throw;
}
cmd.Parameters.AddWithValue("#EQMT", EQMT.Text);
cmd.ExecuteNonQuery();
con.Close();
LoadRecord();
}
}
}
}

How to set checkbox always checked when user redirect to another page?

How do I implement my checkbox to stay check as it is even if user redirects to another page? Example, in my code behind when I check the checkbox the system updates the database and it says "Validated" , but when I press GoBackTeacher_Click event it will redirect to another page. In that another page there is a button function there that will redirect to this current page where my code behind function is implemented and checkbox is checked.
Aspx Code:
<div class="container" style="text-align: center; margin: 0 auto;">
<br />
<h1>Validation of Subjects</h1>
<br />
<asp:GridView runat="server" CssClass="table table-hover table-bordered" ID="ValidateSubject" Style="text-align: center"></asp:GridView>
</div>
<div style="float: right; padding-right: 75px;">
<button type="button" runat="server" class="btn btn-success" onserverclick="GoBackTeacher_Click">Go Back</button>
</div>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace SoftwareAnalysisAndDesign.SAD
{
public partial class ValidateSubjectTeacher : System.Web.UI.Page
{
CheckBox check = new CheckBox();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ValidateSubject"] == null)
{
Response.Redirect("TeacherPage.aspx", true);
}
if (!IsPostBack)
{
ValidateSubject.DataSource = Session["ValidateSubject"];
ValidateSubject.DataBind();
}
//Add a checkbox in the last row of GridView Progmatically
foreach (GridViewRow row in ValidateSubject.Rows)
{
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
}
}
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give row
string validated = "Validated";
string notyetvalidated = "Not yet validated";
string studid = grvRow.Cells[0].Text;
string coursenum = grvRow.Cells[1].Text;
if (chk.Checked)
{
grvRow.Cells[10].Text = validated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber" ,conn))
{
cmd.Parameters.AddWithValue("#Validated", validated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
else
{
grvRow.Cells[10].Text = notyetvalidated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
//query database to update the Status
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber", conn))
{
cmd.Parameters.AddWithValue("#Validated", notyetvalidated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
}
protected void GoBackTeacher_Click(object sender, EventArgs e)
{
Response.Redirect("TeacherPage.aspx");
}
}
}
To further understand my question, here is an image to further explain it.
This is when I check the checkbox without pressing the go back button
And this where I go pressed the go back button and in the another page there is a proceed button to redirect to this current page where my gridview is located.
There the checkbox is unchecked, and the status says it is validated. How do I implement my code that checkbox stay checked?
Is it something to do with postback? Please help.
UPDATE
I've tried this, it will stay checked my redirecting to this page, but when checkbox is clicked the status will not change from "Validated" to "Not yet validated" it will not change on postback when clicked.
foreach (GridViewRow row in ValidateSubject.Rows)
{
bool isChecked = default(bool);
if (row.Cells[row.Cells.Count - 2].Text.Equals("Validated")) // Here please assign the position of **Status** column.
{
isChecked = true;
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
check.Checked = isChecked; //Set checkbox checked based on status ;
}
else if (row.Cells[row.Cells.Count - 2].Text.Equals("Not yet validated"))
{
isChecked = false;
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
check.Checked = isChecked; //Set checkbox checked based on status ;
}
}
In this function, the condition above will not changed the database, instead it will only refresh the page when checkbox is clicked.
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give row
string validated = "Validated";
string notyetvalidated = "Not yet validated";
string studid = grvRow.Cells[0].Text;
string coursenum = grvRow.Cells[1].Text;
if (chk.Checked)
{
grvRow.Cells[10].Text = validated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber" ,conn))
{
cmd.Parameters.AddWithValue("#Validated", validated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
else
{
grvRow.Cells[10].Text = notyetvalidated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
//query database to update the Status
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber", conn))
{
cmd.Parameters.AddWithValue("#Validated", notyetvalidated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
}
You need to modify your Page_Load method in the section where you are iterating inside gridview rows and assigning handlers and setting checkbox property.
In gridview the status column I guess you are saving it at text not a bit so I compared it as text. See following and implement same.
foreach (GridViewRow row in ValidateSubject.Rows)
{
bool isChecked = default(bool);
if (row.Cells[row.Cells.Count - 1].Text.Equals("Validated")) // Here please assign the position of **Status** column.
isChecked = true;
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
check.Checked = isChecked //Set checkbox checked based on status ;
}

ASP.NET Listview.selectedindex property goes crazy

I'm deleting a single database record from a listview and after deleting I try to navigate in my listview using listView1.selectedindex property, but I have noticed that it highlights the incorrect record (for example I set listView1.selectedindex to 1 but it displays a record which has index 0) . What is wrong? Please help!
protected void deleteButton_Click(object sender, EventArgs e)
{
int id = int.Parse(((Label)ListView1.Items[ListView1.SelectedIndex].FindControl("idLabel")).Text);
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
BindDataFromBaseToListView method looks so:
private void BindDataFromBaseToListView()
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("select * from Employee", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
ListView1.DataSourceID = null;
ListView1.DataSource = dTable;
ListView1.DataBind();
}
conn.Close();
}
Instead of using deleteButton_Click event you could use your ListView's OnItemCommand event to get the selected row values and delete the item that you want like the code below:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "delete")
{
int id = 0;
if(int.TryParse((e.Item.FindControl("idLabel") as Label).Text, out id))
{
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
}
}
And on your control's element will look like this:
<asp:ListView ID="ListView1" runat="server" OnItemCommand="ListView1_ItemCommand" .. >
...
<ItemTemplate>
<asp:Button runat="server" CommandName="delete" Text="Delete" ID="DeleteButton" />
...
Let me know if you still have issue with it.

Asp.net markup file

I have been given some c# code and have been asked to create a markup (.aspx) file that would go along with it.
I am not asking for help to write the code, but instead, how to go about it.
Here is the code:
public partial class search : Page
{
protected override void OnLoad(EventArgs e)
{
int defaultCategory;
try
{
defaultCategory = Int32.Parse(Request.QueryString["CategoryId"]);
}
catch (Exception ex)
{
defaultCategory = -1;
}
Results.DataSource = GetResults(defaultCategory);
Results.DataBind();
if (!Page.IsPostBack)
{
CategoryList.DataSource = GetCategories();
CategoryList.DataTextField = "Name";
CategoryList.DataValueField = "Id";
CategoryList.DataBind();
CategoryList.Items.Insert(0, new ListItem("All", "-1"));
CategoryList.SelectedIndex = CategoryList.Items.IndexOf(CategoryList.Items.FindByValue(defaultCategory.ToString()));
base.OnLoad(e);
}
}
private void Search_Click(object sender, EventArgs e)
{
Results.DataSource = GetResults(Convert.ToInt32(CategoryList.SelectedValue));
Results.DataBind();
}
private DataTable GetCategories()
{
if (Cache["AllCategories"] != null)
{
return (DataTable) Cache["AllCategories"];
}
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * From Categories");
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
Cache.Insert("AllCategories", dt, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
connection.Dispose();
return dt;
}
private DataTable GetResults(int categoryId)
{
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * FROM Products P INNER JOIN Categories C on P.CategoryId = C.Id WHERE C.Id = {0} OR {0} = -1", categoryId);
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
connection.Dispose();
return dt;
}
}
EDIT
In the above code, what is the Results object and is the CategoryList just a listbox?
As Nilesh said this seems like a search page, You can possibly try creating the a Webform using Visual studio which is just drag and drop controls into canvas and that will create the mark up for the controls in the code window.
This code behind seems to be doing the following,
On page load at Get request (when its !Page.IsPostBack) page is going to get categories using GetCategories() and fill the drop down list "CategoryList" with all category names (default selected one being the defaultcategory ID from query string).
The search button takes the dropdown's selected value and calls the GetResults() to get data table to fill the grid view "Results". So you need 3 controls (Dropdown list, Button, Gridview) in the webform with these names..

I want my controls value.Insert only one time when I click the button

I have a DropDownlist and a textbox in my page, when I click the button,Button1_Click event fire and get the value od textbox and droppdownlist and send them to my table in database and it shows me the result(new added row in my table in database) in gridview.
my problem is after I click the button if I refresh my page I mean click on reload Current page ,my dropdownlist value and textbox value insert again in my table .
I don't know how solve it?
my gridview use sqldatasource and this is my code:
protected void Button1_Click(object sender, EventArgs e)
{
int brandid = Convert.ToInt32(BrandDropDownList.SelectedValue);
String catname = TextBox2.Text;
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "server = . ; database = mobile_store ; Trusted_Connection=true";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "FirstInitialiseCategories";
cmd.Parameters.AddWithValue("#brandid ", brandid);
cmd.Parameters.AddWithValue("#catname ", catname);
try
{
cn.Open();
cmd.ExecuteNonQuery();
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "با موفقیت ثبت شد!";
SqlDataSource2.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
Label1.ForeColor = System.Drawing.Color.Red;
Label1.Text = "خطا در ثبت!";
}
finally
{ cn.Close(); }
}
You can do a HTTP redirect (to the same page) once you're done with your first insert, it should solve the issue:
Response.Redirect("samePage.aspx");
what is the first item in your dropdown list? you could set a null value to the first item and when you inserted value to database, you can add code to clear the text box and drop down list.
finally
{
cn.Close();
Label1.Text ="";
ddl.SelectedIndex = 0;
}

Resources