On Button click, dropdown loses its value - c#

I have two dropdowns. First is for State and second is one for the City. When I select the state, its respective city gets populated in the next dropdown. I have one option to add more cities through textbox on button click while selecting the Other option from the city dropdownlist.
The issue is that whenever i am adding the city from the textbox, the it gets inserted into the respective state and also the dropdownlist loses its value. I tried debugging but couldn't find the exact issue.
Please see the code for your reference:
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Add_CityforLocation";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = 0;
cmd.Parameters.Add("#CountryName", SqlDbType.VarChar).Value = "India";
cmd.Parameters.Add("#CityName", SqlDbType.VarChar).Value = txtOtherCity.Text.Trim();
cmd.Parameters.Add("#StateName", SqlDbType.VarChar).Value = ddllocation1.SelectedItem.ToString();
cmd.Connection = con;
try
{
cmd.ExecuteNonQuery();
BindContrydropdown();
}
catch (Exception ex)
{
Response.Write(ex.Message);//You Can Haave Messagebox here
}
finally
{
con.Close();
}
}
}
protected void BindContrydropdown()
{
//conenction path for database
//string connection = WebConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select Id,CityName From Career.Location", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddllocation1.DataSource = ds;
ddllocation1.DataTextField = "CityName";
ddllocation1.DataValueField = "Id";
ddllocation1.DataBind();
ddllocation1.Items.Insert(0, new ListItem("--Select--", "0"));
ddllocation1.Items.Insert(1, new ListItem("--OTHER--", "0"));
con.Close();
}
}
Also, see the HTML for the same:-
<tr>
<td class="td">Location/State</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddllocation1" OnSelectedIndexChanged="ddllocation1_SelectedIndexChanged" runat="server" AutoPostBack="true"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="RequiredFieldValidator1" ControlToValidate="ddllocation1" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="td">Location/City</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddlLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlLocation_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="reqLocation" ControlToValidate="ddlLocation" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOtherCity" runat="server" Visible="false" CssClass="txtfld-popup"></asp:TextBox>
<asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
</td>
</tr>

Try this
try
{
if(!IsPostBack)
{
cmd.ExecuteNonQuery();
BindContrydropdown();
}
}

Related

Selected check box in the list view item template is not storing

I'm trying to store the selected rows using asp:checkbox to the CourseParticipants table but it doesn't store the selected records to the database. There is no error shown but it refresh to the same page and shows the checked records. I'm trying to select users.
Thank you in advance!
Here is the markup:
<table class="table table-hover">
<thead style="background-color: #92d36e">
<tr>
<td><b>Employee Name</b></td>
<td><b>Position</b></td>
<td><b>Actions</b></td>
</tr>
</thead>
<tbody>
<asp:ListView ID="lvEmployees" runat="server" OnPagePropertiesChanging="lvEmployees_PagePropertiesChanging" OnDataBound="lvEmployees_DataBound">
<ItemTemplate>
<tr>
<td><%# Eval("FirstName")%>,<%# Eval("LastName")%></td>
<td><%# Eval("Position")%></td>
<td><asp:CheckBox ID="cbEmployee" runat="server" />
</a></td>
</tr>
</ItemTemplate>
</asp:ListView>
</tbody>
</table>
<asp:Button ID="btnAddParticipants" runat="server"
class="btn btn-success" OnClick="btnAddParticipants_Click"
Text="Add Participants" />
Here is the C#
void GetEmployees()
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"SELECT EmployeeID, FirstName, LastName, Position FROM Employees";
using (SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "EmployeeID");
lvEmployees.DataSource = ds;
lvEmployees.DataBind();
con.Close();
}
}
}
protected void btnAddParticipants_Click(object sender, EventArgs e)
{
foreach (ListViewDataItem item in this.lvEmployees.Items)
{
string idValue = lvEmployees.DataKeys[item.DataItemIndex].Value.ToString();
if (item.ItemType == ListViewItemType.DataItem)
{
CheckBox cb = (CheckBox)item.FindControl("cbEmployee");
if (cb.Checked)
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"INSERT INTO CourseParticipants VALUES (#TrainingModuleID, #EmployeeID, #Active, #DateAdded)";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#TrainingModuleID", txtCourseID.Text);
cmd.Parameters.AddWithValue("#EmployeeID", idValue);
cmd.Parameters.AddWithValue("#Active", 1);
cmd.Parameters.AddWithValue("#DateAdded", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
}
If it's always DateTime.Now what you want to insert, you could use the getdate() function:
string query = #"INSERT INTO CourseParticipants VALUES (#TrainingModuleID, #EmployeeID, #Active, getdate())";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#TrainingModuleID", txtCourseID.Text);
cmd.Parameters.AddWithValue("#EmployeeID", idValue);
cmd.Parameters.AddWithValue("#Active", 1);
cmd.ExecuteNonQuery();
}
But it's a bit DB specific, so what DB are you using?
https://learn.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql?view=sql-server-2017
I would also cast/convert txtCourseID.Text to an int (32 or 64) depending on your db scheme. Just to make sure that it's an OK value... and not string (nvarchar).
I also removed the closing of the connection, since it's in a using block.

How to hold the values static on the page

I want to make the values of a text box and labels static on the page when user goes from attendance page to another page I have set the enableviewstate="true" but still its not holding the data when I go to another page it vanishes.
Here is my html code:
<tr>
<td class="auto-style3">Login Time:</td>
<td class="auto-style4">
<asp:Label ID="lblLogin" enableviewstate="true" runat="server"></asp:Label>
</td>
<td class="auto-style5">Logout Time:</td>
<td>
<asp:Label ID="lblLogout" enableviewstate="true" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style3">Remarks:</td>
<td class="auto-style4">
<asp:TextBox ID="TextBoxRemarks" runat="server" enableviewstate="true" TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
Here is my c-sharp code:
TimeSpan logintime = System.DateTime.Now.TimeOfDay;
TimeSpan time = TimeSpan.Parse("09:20:00.000");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblAttendance.Text = Session["user"].ToString().Split('^')[1];
lblDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
if (btnLogin.Text == "Login(Daily Attendance)")
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["REGDataConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("Track_UserLog", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmployeeId", Session["user"].ToString().Split('^')[0]);
cmd.ExecuteNonQuery();
con.Close();
lblLogin.Text = System.DateTime.Now.ToString("hh:mm");
btnLogin.Text = "Logout(Daily Attendance)";
if (logintime > time)//&& TextBoxRemarks.Text.ToString() == String.Empty)
{
DateTime today = DateTime.Today;
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["REGDataConnectionString"].ConnectionString);
cn.Open();
SqlCommand cd = new SqlCommand("update tblAttendanceDetails set Remarks=#rem where LoginDate=convert(date,GETDATE()) AND EmployeeId=' " + Session["User"].ToString().Split('^')[0] + " '", cn);
cd.Parameters.AddWithValue("#rem", TextBoxRemarks.Text);
cd.ExecuteNonQuery();
cn.Close();
}
}
else if (btnLogin.Text == "Logout(Daily Attendance)")
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["REGDataConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("Track_logout", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmployeeId", Session["user"].ToString().Split('^')[0]);
cmd.ExecuteNonQuery();
lblLogout.Text = System.DateTime.Now.ToString("hh:mm");
btnLogin.Text = "Login(Daily Attendance)";
}
}
Viewstate works for only same page postbacks.
From MSDN:
View state provides state information for a specific ASP.NET page. If you need to use information on more than one page, or if you need the information to persist across visits to the Web site, you must use another method for maintaining state. You can use application state, session state, or profile properties.
If you want to see same data when you get request that page you should store data in application state, session state, or profile properties.
Then you should manually bind this data to pages elements.

Dropdown value disappears after submit

I have a textbox whose values goes into the dropdown on button click. The problem is that when I fill all the data and submit the form. And when I come second time to see that value it disappears from the dropdown. What should I do to make the value gets in the dropdown fix. Please see the code for your reference:
<tr>
<td class="td">Location/City</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddlLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlLocation_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="reqLocation" ControlToValidate="ddlLocation" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOtherCity" runat="server" Visible="false" CssClass="txtfld-popup"></asp:TextBox>
<asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
</td>
</tr>
Also, see the code behind for your reference:-
protected void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLocation.SelectedItem.Text == "Other")
{
txtOtherCity.Visible = true;
}
else
{
txtOtherCity.Visible = false;
}
}
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
string city = txtOtherCity.Text.Trim();
if (!string.IsNullOrEmpty(city))
{
ddlLocation.Items.Add(new ListItem(city, city));
}
}
You have to store the values from the textbox into the table dbo.Cities in database. Next time when you will come back to the same page then dropdown will fetch data from db.
Then on btnAddDropDown_Click1() you should insert the value of the city from the 'txtOtherCity' TextBox to the respective table, and then bind the DropDown of the city again. Something Like
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
string strconnection = System.Configuration.ConfigurationManager.AppSettings["YourConnectionString"].ToString();
string city = txtOtherCity.Text.Trim();
DataSet ds=new DataSet();
if (!string.IsNullOrEmpty(city))
{
// Your code to insert the value of the city from the 'txtOtherCity' `TextBox` to the respective table
//Edit: this is a very rudimentary code
string query = "INSERT INTO Career.Location (State) " +
"VALUES (#city) ";
// create connection and command
using(SqlConnection cn = new SqlConnection(strconnection))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("#city", SqlDbType.VarChar, 50).Value = city;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
query = "select State from Career.Location";
using(SqlConnection cnn = new SqlConnection(strconnection))
using(SqlCommand cmdd = new SqlCommand(query, cnn))
{
SqlDataAdapter adp = new SqlDataAdapter(cmdd);
cnn.Open();
adp .Fill(ds);
cnn.Close();
}
ddlLocation.DataSource=ds;
ddlLocation.DataTextField = "State";
ddlLocation.DataValueField = "State";
ddlLocation.DataBind();
}
}
Do you have functionality of inserting the data in the DB (not only adding the new item in the drop down list). You have to insert the city in the appropriate table to be able to see it later on.
The implementation depends on your architecture, the implementation of the DAL etc.
For example - if you are using ADO.NET, you can insert the values in the table with a stored procedure:
CREATE PROCEDURE Add_City
#CityName varchar(50),
#StateID int
AS
BEGIN
INSERT INTO dbo.Cities (CityName, StateID) values (#CityName, #StateID)
END
GO
And then call it from the app. Something like that:
using (SqlConnection con = new SqlConnection("the connection string"))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Add_City";
cmd.Parameters.Add("#CityName", SqlDbType.VarChar).Value = txtCity.Text.Trim();
cmd.Parameters.Add("#StateID", SqlDbType.Int).Value = CountryId;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
// lblMessage.Text = "City inserted successfully!";
}
catch (Exception ex)
{
throw ex; // Or log or handle somehow the exception
}
}
I got the answer for this solution, Please see the code for your reference:-
protected void BindContrydropdown()
{
//conenction path for database
//string connection = WebConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select Id,CityName From Career.Location", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddllocation1.DataSource = ds;
ddllocation1.DataTextField = "CityName";
ddllocation1.DataValueField = "Id";
ddllocation1.DataBind();
ddllocation1.Items.Insert(0, new ListItem("--Select--", "0"));
ddllocation1.Items.Insert(1, new ListItem("--OTHER--", "0"));
con.Close();
}
}
protected void ddllocation1_SelectedIndexChanged(object sender, EventArgs e)
{
string country = "India";
var cities = _helper.GetLocations(country, ddllocation1.SelectedValue);
cities.Insert(0, "--Select--");
cities.Insert(1, "Other");
ddlLocation.DataSource = cities;
ddlLocation.DataBind();
}
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
//BindContrydropdown();
//if (txtOtherCity.Text != "")
//{
// txtOtherCity.Text = "";
//}
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Add_CityforLocation";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = 0;
cmd.Parameters.Add("#CountryName", SqlDbType.VarChar).Value = "India";
cmd.Parameters.Add("#CityName", SqlDbType.VarChar).Value = txtOtherCity.Text.Trim();
cmd.Parameters.Add("#StateName", SqlDbType.VarChar).Value = ddlLocation.SelectedItem.ToString();
cmd.Connection = con;
try
{
// con.Open();
cmd.ExecuteNonQuery();
BindContrydropdown();
// lblMessage.Text = "City inserted successfully!";
}
catch (Exception ex)
{
Response.Write(ex.Message);//You Can Haave Messagebox here
}
finally
{
con.Close();
}
}
}
Also see the html of the dropdowns:-
<tr>
<td class="td">Location/State</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddllocation1" OnSelectedIndexChanged="ddllocation1_SelectedIndexChanged" runat="server" AutoPostBack="true"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="RequiredFieldValidator1" ControlToValidate="ddllocation1" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="td">Location/City</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddlLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlLocation_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="reqLocation" ControlToValidate="ddlLocation" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOtherCity" runat="server" Visible="false" CssClass="txtfld-popup"></asp:TextBox>
<asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
</td>
</tr>
And this solved my,
Also see the Stored procedure for the same:-
Alter PROCEDURE [dbo].[Add_CityforLocation]
-- Add the parameters for the stored procedure here
#ID int,
#CountryName nvarchar(100),
#StateName nvarchar(100),
#CityName varchar(100)
AS
BEGIN
INSERT INTO Career.Location(CountryName, StateName, CityName) values (#CountryName,#StateName,#CityName)
END
GO

OnSelectedIndexChanged event not working

i am trying to get data from the stored procedure into the dropdownlist when the event onSelectIndexChanged is fired. But after putting the break point i get to know that the event generated is not working i.e. the control doesnot even goes into that code.
<tr>
<td><asp:Label ID="Label5" runat="server" Text="Book Category"></asp:Label></td>
<td>
<asp:DropDownList ID="ddlBookCategory" runat="server" Height="20px" Width="250px" OnSelectedIndexChanged="ddlBookCategory_SelectedIndexChanged" >
</asp:DropDownList>
</td>
</tr>
<tr>
<td><asp:Label ID="Label4" runat="server" Text="Book Subject"></asp:Label></td>
<td>
<asp:DropDownList ID="ddlBookSubject" runat="server" Height="20px" Width="250px" >
</asp:DropDownList>
</td>
</tr>
and the backend cs file coding is::
protected void Page_Load(object sender, EventArgs e)
{
connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
lblmsg.Visible = false;
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
try
{
con.Open();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "ShowBookCategory";
cmd.Connection = con;
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
ddlBookCategory.Items.Add(new ListItem(reader["CategoryName"].ToString()));
}
}
}
catch (OleDbException ex)
{
ex.Data.ToString();
}
}
protected void ddlBookCategory_SelectedIndexChanged(object sender, EventArgs e)
{
ddlBookCategory.AutoPostBack = true;
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd2 = new OleDbCommand();
MbERPLibraryBookSubjectProperty foc = new MbERPLibraryBookSubjectProperty();
try
{
con.Open();
cmd2.CommandType = System.Data.CommandType.StoredProcedure;
cmd2.CommandText = "ShowBookSubjectWithCategory";
cmd2.Connection = con;
foc.CategoryName = ddlBookCategory.Text.ToString();
cmd2.Parameters.Add(new OleDbParameter("#CategoryName", foc.CategoryName));
cmd2.Parameters["#CategoryName"].Direction = System.Data.ParameterDirection.Input;
OleDbDataReader reader2 = cmd2.ExecuteReader();
if (reader2.HasRows)
{
while (reader2.Read())
{
ddlBookSubject.Items.Add(new ListItem(reader2["SubjectName"].ToString()));
}
}
}
catch (OleDbException ex)
{
ex.Data.ToString();
}
}
And my stored Procedure is:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[ShowBookSubjectWithCategory](
#CategoryName varchar(50)
)
AS
BEGIN
select * from BookSubjects Where CategoryName = #CategoryName
END
Instead of declaring autoPostBack as true in your event handler, try to set it in DropDownList declaration like bellow:
<asp:DropDownList ID="ddlBookCategory" ... autopostback="true" ... >
...
</asp:DropDownList>
If you want to set ddlBookCategory.AutoPostBack = true; dynamically then set that in pageload event.
You need to add AutoPostBack =true to the control in order for the control to signal back to the server that an event has occurred. Once you do that you can set an event handler to a method in your code behind for the selected index changed event on that control.

Cannot refresh Listview after ItemCommand event is fired

I've a listview that allows Editing and Delete.
When I Click on the linkbutton in the listview, it fires up page_load then to OnItemCommand.
At the end of the command I added DataBind Which does not refresh my listview but deleted my entry.
If I change the DataBind to Redirect back to the same page with (...aspx?ID=...) it will return me a fresh new page. but in debug mode, I saw it run through page_load and the Databind.
<asp:UpdatePanel ID="UpdateOptions" runat="server" >
<ContentTemplate>
<asp:Panel ID="OPanel" runat="server" width="350px">
<asp:ListView runat="server" ID="lvPollOptions" DataKeyNames="POptionID" OnItemCommand="lvPollOptions_ItemCommand" OnDataBound="lvPollOptions_ItemDataBound" >
<LayoutTemplate>
<table cellpadding="0" cellspacing="0" border="0" width="300px">
<tr class="AdminListHeader">
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<%#Eval("OptionText")%>
</td>
<td>
<%#Eval("Votes")%>
</td>
<td align="center">
<asp:ImageButton runat="server" ID="ibtnEditOption" CommandArgument='<%# Eval("POptionID").ToString() %>' CommandName="Edit" ImageUrl="~/images/buttons/EditPencil.gif" AlternateText="Edit" CssClass="AdminImg" />
</td>
<td>
<asp:ImageButton runat="server" ID="ibtnDeleteOption" CommandArgument='<%# Eval("POptionID").ToString() %>' CommandName="Delete" ImageUrl="~/images/buttons/delete.gif" AlternateText="Delete" CssClass="AdminImg" OnClientClick="return confirm('Warning: This will delete the Poll Option from the database.');" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Label ID="lblNoOption" runat="server" Text="No Options Added"></asp:Label>
<table width="345px">
<tr>
<td width="100px">
Option:
</td>
<td>
<asp:TextBox ID="txtOption" runat="server" width="200px"></asp:TextBox>
</td>
</tr>
</table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind
protected void PollBindData()
{
SqlConnection connOption = new SqlConnection(connStr);
connOption.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT POptionID, OptionText, Votes FROM [PollOptions] Where PollID = '" + PID + "'", connOption);
DataSet dsSel = new DataSet();
da.Fill(dsSel);
lvPollOptions.DataSource = dsSel;
lvPollOptions.DataBind();
connOption.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
string PID = Request.QueryString["ID"];
if (!IsPostBack)
{
if (PID == null)
{
}
else if (PID != null)
{
PollBindData();
}
}
}
protected void lvPollOptions_ItemDataBound(object sender, ListViewItemEventArgs e)
{
string PID = Request.QueryString["ID"];
SqlConnection connOption = new SqlConnection(connStr);
connOption.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT POptionID, OptionText, Votes FROM [PollOptions] Where PollID = '" + PID + "'", connOption);
DataSet dsSel = new DataSet();
da.Fill(dsSel);
lvPollOptions.DataSource = dsSel;
lvPollOptions.DataBind();
connOption.Close();
}
protected void lvPollOptions_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
string selectedID = e.CommandArgument.ToString();
SqlConnection connDeleteOption = new SqlConnection(connStr);
connDeleteOption.Open();
SqlCommand cmdDeleteOption = new SqlCommand("DELETE FROM [PollOptions] WHERE POptionID = '" + selectedID + "'", connDeleteOption);
cmdDeleteOption.ExecuteNonQuery();
connDeleteOption.Close();
PollBindData();
//Response.Redirect("aAddEditPoll.aspx?ID=" + selectedID);
}
if (e.CommandName == "Edit")
{
string EditID = e.CommandArgument.ToString();
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmdView = new SqlCommand("SELECT OptionText From [PollOptions] Where POptionID = '" + EditID + "'", conn);
SqlDataReader dr1 = cmdView.ExecuteReader();
if (dr1.Read())
{
txtOption.Text = dr1["OptionText"].ToString();
}
Session["OptionID"] = txtOption.Text;
dr1.Close();
conn.Close();
lbOInsert.Visible = false;
lbOUpdate.Visible = true;
PollBindData();
//Response.Redirect("aAddEditPoll.aspx?ID=" + EditID);
}
}
Before we start - your code has a security risk since it is prone to Sql Injection, make sure you Parametrize your queries...
Now, your question is not very clear, but if I understand correctly, you're saying that after you delete an object, the Listview isn't refreshed after postback (e.g. you still see the deleted item). Since you're running in an UpdatePanel, make sure to update the panel after the DataBind...
Update PoolBindData like this
protected void PollBindData()
{
SqlConnection connOption = new SqlConnection(connStr);
connOption.Open();
// POTENTIAL SECURITY RISK - MAKE SURE YOU PARAMETRIZE THE QUERY!!
SqlDataAdapter da = new SqlDataAdapter("SELECT POptionID, OptionText, Votes FROM [PollOptions] Where PollID = '" + PID + "'", connOption);
DataTable dsSel = new DataTable();
da.Fill(dsSel);
lvPollOptions.DataSource = dsSel;
lvPollOptions.DataBind();
connOption.Close();
// Update panel
UpdateOptions.Update();
}

Categories