ListView cancel editItem - c#

I'm having trouble returning to listview and cancelling the edit of items using ASP and C#.
I already have the same answer as this
but I'm still getting the error message of Cancel can only be called from the currently-edited record or an insert item.
Here is the offending code - any pointers on what is causing this would be very useful:
I also have a layout, selected template, and insert which are all identical.
<asp:ListView ID="ListView1" runat="server" DataSourceID="sqlDatasource1"
EnableViewState="true" DataKeyNames="EndUserId" AllowPaging="True"
OnItemCommand="ListView1_ItemCommand" OnItemCanceling="ListView1_ItemCanceling">
<EditItemTemplate>
<tr>
<asp:Label runat="server" ID="tbId" Text='<%#Eval("EndUserId") %>' Visible="false" />
<td>
<asp:TextBox runat="server" ID="tbEmail" Text='<%#Eval("Email") %>' />
</td>
<td>
<asp:TextBox runat="server" ID="tbRole" Text='<%#Eval("Role") %>' />
</td>
<td>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</td>
</tr>
</EditItemTemplate>
c# backend controlling
protected void ListView1_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
ListView1.EditIndex = -1;
ListView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
ListView1.EditIndex = -1;
ListView1.InsertItemPosition = InsertItemPosition.LastItem;
if (!IsPostBack)
{
}
}
added backend
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
Label tbId = (Label)e.Item.FindControl("tbId");
TextBox tbEmail = (TextBox)e.Item.FindControl("tbEmail");
TextBox tbPass = (TextBox)e.Item.FindControl("tbPass");
string updateCommand =
"UPDATE [EndUser_tbl] SET [Email]='" +
tbEmail.Text + "', [Password]='" + tbPass.Text +
"'WHERE EndUserId=" + Convert.ToInt32(tbId.Text) + ";";
sqlDatasource1.UpdateCommand = updateCommand;
}
if (e.CommandName == "Delete")
{
Label id = (Label)e.Item.FindControl("tbId");
string deleteCommand = "DELETE FROM [EndUser_tbl] " +
"WHERE EndUserId=" + Convert.ToInt32(id.Text);
sqlDatasource1.DeleteCommand = deleteCommand;
}
if (e.CommandName == "Insert")
{
TextBox tbEmail = (TextBox)e.Item.FindControl("tbEmail");
TextBox tbPass = (TextBox)e.Item.FindControl("tbPass");
string insertCommand = "INSERT INTO [EndUser_tbl] " +
"([Email],[Password],[ContractRef],[Role])" +
"VALUES ('" + tbEmail.Text + "','" + tbPass.Text +
"','" + tbPass.Text + "');";
sqlDatasource1.InsertCommand = insertCommand;
}
}

Change the Page_load like this way:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListView1.EditIndex = -1;
ListView1.InsertItemPosition = InsertItemPosition.LastItem;
}
}
And try it again.

Related

drop downlist value keep changing after selectedIndexChange

I have two dropdown list named dl_bankName,dl_branch and a textbox named txt_bankCode.dl_bankName will be filled on pageLoad and dl_branch will get filled on the selectedIndexChange of dl_bankName and txt_bankCode will be filled on the selectedIndexChange of dl_branch. dl_bankName is filled and the selected value is retained even after postBack but dl_branch name is changed to the first value when we select other values.
my sample code is given below
HTML
<asp:DropDownList ID="dl_bankName" runat="server" Width="230px"
Height="22px" AutoPostBack="True" onselectedindexchanged="dl_bankName_SelectedIndexChanged"> </asp:DropDownList>
<asp:DropDownList ID="dl_BranchName" Width="230px" Height="22px" runat="server"
onselectedindexchanged="dl_BranchName_SelectedIndexChanged"
AutoPostBack="True"></asp:DropDownList>
<asp:TextBox ID="txt_IfscMicr" runat="server" CausesValidation="true"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="txt_IfscMicr" runat="server" ID="RequiredFieldValidator9" ErrorMessage="*" Font-Size="Large" ForeColor="#FF5050" />
CODE
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
filldl_bankName();
}
}
protected void dl_bankName_SelectedIndexChanged(object sender, EventArgs e)
{
if (dl_BranchName.DataSource == null)
{
filldl_BranchName();
}
txt_IfscMicr.Text = "";
}
protected void dl_BranchName_SelectedIndexChanged(object sender, EventArgs e)
{
filltxt_IfscMicr();
}
protected void filldl_bankName()
{
string query = "select '--Select--' as bank_name,'0' as bank_code from DUAL union all select distinct(bank_name),bank_code from em_bank_details ";
dl_bankName.DataSource = GetDt(query);
dl_bankName.DataTextField = "bank_name";
dl_bankName.DataValueField = "bank_code";
dl_bankName.DataBind();
}
protected void filldl_BranchName()
{
string query = "select '--Select--' as branch_name,'0' as bank_code from DUAL union all select distinct(branch_name),bank_code from em_bank_details where bank_name='" + dl_bankName.SelectedItem.Text + "'";
dl_BranchName.DataSource = GetDt(query);
dl_BranchName.DataTextField = "branch_name";
dl_BranchName.DataValueField = "bank_code";
dl_BranchName.DataBind();
}
protected void filltxt_IfscMicr()
{
string query = "select distinct(branch_code),bank_code from em_bank_details where bank_name='" + dl_bankName.SelectedItem.Text + "' and branch_name='" + dl_BranchName.SelectedItem.Text + "'";
txt_IfscMicr.Text = GetDt(query).Rows[0]["branch_code"].ToString();
}
I've solved the issue by commenting the code line
dl_BranchName.DataValueField = "bank_code";
in the function filldl_BranchName() . The bank_code was all same for all the branch_name maybe that's what cause the issue .Now everything is working as per my requirement.

How to insert text and value from checkbox in datalist into sql server

i have datalist filled by checkbox. the code like this
the form
<asp:DataList ID="DataListTest" runat="server" OnPreRender="PreTes">
<ItemTemplate>
<table cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:Label ID="lblHeader" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td><asp:Label ID="lblsubheader" runat="server" /></td>
</tr>
<tr>
<td>
<asp:HiddenField ID="subhd" runat="server" Value='<%# Eval("sub_category") %>' />
</td>
</tr>
<tr>
<td>
<asp:CheckBox ID="cbNameAccess" runat="server" Text='<%# Eval("name_access") %>' />
<asp:HiddenField ID="hd" runat="server" Value='<%# Eval("name_category") %>' />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
the code to get data from database
private void ShowDataList()
{
conn.Open();
string sql = "Select access.id_access, access.nama_access, jenis_access.id_jenis_access ,jenis_access.nama_jenis_access as 'nama_jenis', sub_jenis.nama_sub_jenis as 'sub_jenis',sub_jenis.id_sub_jenis "+
"FROM access LEFT JOIN detil_access ON access.id_access = detil_access.id_access "+
"LEFT JOIN jenis_access ON detil_access.id_jenis_access = jenis_access.id_jenis_access "+
"LEFT JOIN sub_jenis ON detil_access.id_sub_jenis = sub_jenis.id_sub_jenis "+
"ORDER BY jenis_access.id_jenis_access";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
dt = new DataTable();
adp.Fill(dt);
DataListTest.DataSource = dt;
DataListTest.DataBind();
}
the code to show data from database into datalist and show it as Checkbox
protected void PreTes(object sender, EventArgs e)
{
string temp = "";
string subtemp ="";
foreach (DataList item in DataListTest.Items)
{
Label objLabel = item.FindControl("lblHeader") as Label;
Label subjenis = item.FindControl("lblsubheader") as Label;
CheckBox objName = item.FindControl("cbCountryName") as CheckBox;
HiddenField objHD = item.FindControl("hd") as HiddenField;
HiddenField subobjHD = item.FindControl("subhd") as HiddenField;
if (temp != objHD.Value)
{
temp = objHD.Value;
objLabel.Text = temp + "<br/>";
}
if (subtemp != subobjHD.Value)
{
subtemp = subobjHD.Value;
subjenis.Text = subtemp+"<br/>";
}
}
}
the code for insert into sql
private void InsertActivationDetail()
{
// get idActivation
int MaxActivationId = GetGenerateActivationID();
//
foreach (DataList objitem in DataListTest.Items)
{
if (objitem.Selected)
{
conn.Open();
sql = "INSERT INTO detil_activation (id_activation_access, id_jenis_access, id_access, " +
"others_all, others_nama_access, call_back_to, reason_any_number, description_other_jenis_access, " +
"reason_others_jenis_access) VALUES ('" +
MaxActivationId + "', (select id_jenis_access from access where id_access = '" +
objitem.Value + "'), '" + objitem.Value + "',NULL,NULL,NULL,NULL,NULL,NULL)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
my question is "How to insert id and name(text and value) from checkbox into database sql server"
i think the problem is around function InsertActivationDetail(). because i have red underline on it. Would you mind to help me please ?
FYI = i'm a newbie in here also programmer.
Try this. Modified your Method a little. Your are not getting the CheckBox within your DataList.
private void InsertActivationDetail()
{
// get idActivation
int MaxActivationId = GetGenerateActivationID();
//
foreach (DataListItem objitem in DataListTest.Items)
{
CheckBox cbNameAccess = (CheckBox)objitem.FindControl("cbNameAccess");
if (cbNameAccess != null)
{
if (cbNameAccess.Checked==true)
{
conn.Open();
sql = "INSERT INTO detil_activation (id_activation_access, id_jenis_access, id_access, " +
"others_all, others_nama_access, call_back_to, reason_any_number, description_other_jenis_access, " +
"reason_others_jenis_access) VALUES ('" +
MaxActivationId + "', (select id_jenis_access from access where id_access = '" +
cbNameAccess.Text + "'), '" + cbNameAccess.Text + "',NULL,NULL,NULL,NULL,NULL,NULL)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
}
}

How to bind values in usercontrol dropdownlist?

I bind the values in usercontrol dropdownlist
But when I add the usercontrol row that time values are not binded in dropdownlist
Code:
.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TimesheetUserControl.ascx.cs" Inherits="Portal.TimesheetUserControl" %>
<table>
<tr>
<td>
<asp:DropDownList ID="DropDownActivities" Width="150px" runat="server"></asp:DropDownList>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
</td>
</tr>
.aspx
<uc:Timesheet ID="Timesheet" runat="server" />
<asp:Repeater ID="rpt1" runat="server">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"/>
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
{
BindActivities();
}
}
protected void BindActivities()
{
DropDownList dropActivities = Timesheet.FindControl("DropDownActivities") as DropDownList;
DbConnection.Open();
OleDbCommand cmd1 = new OleDbCommand("select designation from emp_master where username = '" + username + "'", DbConnection);
OleDbDataAdapter da = new OleDbDataAdapter(Deptcmd);
DataSet ds = new DataSet();
da.Fill(ds);
// DbConnection.Close();
dropActivities.DataSource = ds;
dropActivities.DataTextField = "ActivityName";
dropActivities.DataBind();
dropActivities.Items.Insert(0, new ListItem("--Select--", "0"));
}
public List<string> NoOfControls
{
get
{
return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];
}
set
{
ViewState["NoOfControls"] = value;
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (IsPostBack)
{
GenerateControls();
}
}
private void GenerateControls()
{
foreach (string i in NoOfControls)
{
TimesheetUserControl ctrl = (TimesheetUserControl)Page.LoadControl("TimesheetUserControl.ascx");
ctrl.ID = i;
this.rpt1.Controls.Add(ctrl);
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
Button thisButton = (Button)sender;
List<string> temp = null;
var uc = (TimesheetUserControl)this.LoadControl(#"TimesheetUserControl.ascx");
string id = Guid.NewGuid().ToString();
uc.ID = id;
temp = NoOfControls;
temp.Add(id);
NoOfControls = temp;
rpt1.Controls.Add(uc);
}
In the below image if Click add button rows are added but in second values are not binded in dropdownlist
Any ideas? Thanks in advance.
find the user controls by the id you given and then you can find the DropDownList inside the usercontrol.
protected void BindActivities()
{
foreach (string controlName in NoOfControls)
{
TimesheetUserControl userControl = Timesheet.FindControl(controlName) as TimesheetUserControl;
if(userControl == null) return;
DropDownList dropActivities = userControl.FindControl("DropDownActivities") as DropDownList;
if(dropActivities == null) return;
DbConnection.Open();
OleDbCommand cmd1 = new OleDbCommand("select designation from emp_master where username = '" + username + "'", DbConnection);
OleDbDataAdapter da = new OleDbDataAdapter(Deptcmd);
DataSet ds = new DataSet();
da.Fill(ds);
// DbConnection.Close();
dropActivities.DataSource = ds;
dropActivities.DataTextField = "ActivityName";
dropActivities.DataBind();
dropActivities.Items.Insert(0, new ListItem("--Select--", "0"));
}
}

UPDATE data through listview and textbox sql server compact 4

I have made an database application. At the moment i have a add and delete function, but now i am searching for help with the update function. I have searched all over this website for an answer, but no luck i guess. So what i want is that if i click on a record in the ListView that it automatically shows up in the textboxes so that i can change things, and when i click the button "Update" it has to update the record.
Help will be extremely appreciated!
my code of Form1
public SqlCeConnection conn = new SqlCeConnection(#"Data Source=E:\Users\Ali\Documents\automail.sdf");
////////////////////////////////////Methodes////////////////////////////////////
private void Populate()
{
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM Emails ORDER BY principalID", conn);
listView1.Items.Clear();
try
{
SqlCeDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
ListViewItem it = new ListViewItem(dr["principalID"].ToString());
it.SubItems.Add(dr["email"].ToString());
it.SubItems.Add(dr["query"].ToString());
it.SubItems.Add(dr["subject"].ToString());
listView1.Items.Add(it);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Application.ExitThread();
}
}
////////////////////////////////////Methodes////////////////////////////////////
// Insert button (for data insert)
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
MessageBox.Show("Fill in all the information first!");
}
else
{
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Emails(principalID, email, query, subject) VALUES(#principalID, #email, #query, #subject)", conn);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#principalID", textBox1.Text);
cmd.Parameters.AddWithValue("#query", textBox2.Text);
cmd.Parameters.AddWithValue("#email", textBox3.Text);
cmd.Parameters.AddWithValue("#subject", textBox4.Text);
try
{
int affectedrows = cmd.ExecuteNonQuery();
if (affectedrows > 0)
{
Populate();
MessageBox.Show("Email added successfully!");
}
else
{
MessageBox.Show("Failed to add email!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//if form shown update listview
private void Form1_Shown(object sender, EventArgs e)
{
try
{
conn.Open();
Populate();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
Application.ExitThread();
}
}
//open form 2 and hide this
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//if listview selected enable button, else disable
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
button3.Enabled = true;
}
else
{
button3.Enabled = false;
}
}
private void button3_Click(object sender, EventArgs e)
{
}
//delete record button
private void button3_Click_1(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count <= 0)
{
MessageBox.Show("Select a record!");
}
else
{
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
SqlCeCommand cm = new SqlCeCommand("DELETE FROM Emails WHERE principalID = #principalID", conn);
cm.Parameters.AddWithValue("#principalID", listView1.SelectedItems[0].Text);
try
{
cm.ExecuteNonQuery();
Populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void button2_Click_1(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
ListViewItem itm = listView1.SelectedItems[0];
string principalid = itm.SubItems[0].Text;
string query = itm.SubItems[1].Text;
string email = itm.SubItems[2].Text;
Form2 form2 = new Form2();
form2.Show();
form2.PrincipalID = principalid;
form2.Query = query;
form2.Email = email;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
}
}
}
Why are you using listview.You can use datagridview instead.You can bind the database file with datagridview which would create update,select and insert command itself.
I don't see why you cannot do so. It's relatively easy in listview to update an item.
You need to create EditItemTemplate, for your ListView, so that textboxes appear in your row to be edited.
you can handle this in ItemEditing event.
and then you handle update through ItemUpdating event of ListView.
below am posting a sample example: it might help you out:
create your ListView markup like this:
<asp:ListView ID="lvwTest" runat="server" OnItemDeleting="lvwTest_ItemDeleting" OnItemEditing="lvwTest_ItemEditing"
OnItemUpdating="lvwTest_ItemUpdating">
<LayoutTemplate>
<table>
<tr>
<td>
Column1
</td>
<td>
Column2
</td>
<td>
Column3
</td>
<td>
Action
</td>
</tr>
<tr id="itemplaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lbl1" runat="server" Text='<%#Eval("col1") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("col2") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("col3") %>'></asp:Label>
</td>
<td>
<asp:Button ID="btnEdit" CommandName="Edit" runat="server" Text="Edit" />
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr>
<td>
<asp:TextBox ID="txt1" runat="server" Text='<%#Bind("col1") %>'></asp:TextBox>
</td>
<td>
<asp:TextBox ID="txt2" runat="server" Text='<%#Bind("col2") %>'></asp:TextBox>
</td>
<td>
<asp:TextBox ID="txt3" runat="server" Text='<%#Bind("col3") %>'></asp:TextBox>
</td>
<td>
<asp:Button ID="btnUpdate" CommandName="Update" Text="Update" runat="server" />
<asp:Button ID="btnCancel" CommandName="Cancel" Text="Cancel" runat="server" />
</td>
</tr>
</EditItemTemplate>
</asp:ListView>
so basically you've created EditItemTemplate.
See how ItemTemplate has a button "btnEdit" in the last column and EditItemTemplate has two buttons "btnUpdate" and "btnCancel" instead of that with appropriate CommandName.
now here are your events:
ItemEditing:
protected void lvwTest_ItemEditing(object sender, ListViewEditEventArgs e)
{
lvwTest.EditIndex = e.NewEditIndex;
}
ItemUpdating:
protected void lvwTest_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
TextBox txt = (lvwTest.Items[e.ItemIndex].FindControl("txt1")) as TextBox;
//as above find othe textboxes as well/
//create your update query
//SqlCeCommand cmd = new SqlCeCommand(updateQuery, cn);
//and rest of the syntax
lvwTest.EditIndex = -1;
BindGrid();
}
your datasource:
public void BindGrid()
{
DataTable db = new DataTable();
db.Columns.Add("col1");
db.Columns.Add("col2");
db.Columns.Add("col3");
db.Rows.Add("1", "2", "3");
db.Rows.Add("1", "2", "3");
db.Rows.Add("1", "2", "3");
lvwTest.DataSource = db;
lvwTest.DataBind();
}
inside page's Page_Load
if (!IsPostBack)
BindGrid();

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