Disregard Changes in input fields/dropdown using ASP.NET C# - c#

So I am new to ASP.NET C# and having trouble in creating a cancel function. When the cancel function click it supposedly discard all the changes the user made inside the inputfield/dropdown and return to it's previous value before the modification has made. Is there any way to this kind of function? thanks in advance.
this is a sample scenario :
As you can see in the photo, the user has made some modification in the selected row in gridview and when the click the cancel button, the changes should be disregarded and turn back to it's previous value .
Inputbo/dropdown part
<table class="style2" >
<tr>
<td class="style3" >Department Case #</td>
<td> <asp:TextBox ID="TextBox1" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
<tr>
<td class="style3">Department</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server"
Height="18px" Width="153px" Enabled="False" AppendDataBoundItems="true"
AutoPostBack="true" DataSourceID="SqlDataSource2"
DataTextField="DEPARTMENT_NAME" DataValueField="DEPARTMENT_CODE"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" >
<asp:ListItem Text="--- Select ----" Value=" " />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:*****ConnectionString %>"
SelectCommand="SELECT [DEPARTMENT_CODE], [DEPARTMENT_NAME] FROM [TV_DEPTNAME]">
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td class="style3">Charge</td>
<td>
<asp:DropDownList ID="DropDownList2" runat="server"
Height="22px" Width="153px" Enabled="False" AppendDataBoundItems="true"
AutoPostBack="true" DataSourceID="SqlDataSource3"
DataTextField="OFFENSE_DESCRIPTION" DataValueField="OFFENSE_CODE"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" >
<asp:ListItem Text="--- Select ----" Value=" " />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:****ConnectionString %>"
SelectCommand="SELECT [OFFENSE_CODE], [OFFENSE_DESCRIPTION] FROM [TV_OFFENSE]">
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td class="style3">Lab Case #</td>
<td><asp:TextBox ID="TextBox4" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
<tr>
<td class="style3">Incident Report Date</td>
<td><asp:TextBox ID="TextBox5" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
</table>
button part
<asp:TextBox ID="TextBox6" runat="server" Visible="False"></asp:TextBox>
<br />
<asp:Button ID="btnEdit" runat="server" onclick="btnEdit_Click" Text="Edit" />
<asp:Button ID="btnSave" runat="server" onclick="btnSave_Click" Text="Save" Enabled="false"/>
<asp:Button ID="btnCancel" runat="server" onclick="btnCancel_Click" Text="Cancel" Enabled="false"/>
<br />
CODE BEHIND
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{ ///<summary> Change the mouse cursor to Hand symbol to show the user the cell is selectable</summary>
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';this.style.cursor='Pointer'";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
///<summary> Attach the click event to each cells</summary>
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
}
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Select")
{
///<summary>
///Convert the row index stored in the CommandArgument
///property to an Integer.
///</summary>
LoadData(Convert.ToInt32(e.CommandArgument));
}
}
private void LoadData(int? rowNumber = null)
{
//if rowNumber is null use GridView1.SelectedIndex
var index = rowNumber ?? GridView1.SelectedIndex;
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = GridView1.Rows[index];
//Populate the input box with the value of selected row.
GridViewRow gr = GridView1.Rows[index];
TextBox1.Text = gr.Cells[2].Text;
TextBox7.Text = gr.Cells[3].Text;
TextBox8.Text = gr.Cells[4].Text;
TextBox4.Text = gr.Cells[5].Text;
TextBox5.Text = gr.Cells[6].Text;
TextBox6.Text = gr.Cells[1].Text;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{ // to set the value of the selected item in dropdown
DropDownList1.SelectedValue = DropDownList1.SelectedItem.Value;
DropDownList2.SelectedValue = DropDownList2.SelectedItem.Value;
}
protected void btnEdit_Click(object sender, EventArgs e)
{ ///<summary> Disabling/Enabling of input fields and button when a certain button is clicked</summary>
SetEnable(true);
}
protected void btnSave_Click(object sender, EventArgs e)
{ ///<summary> Disabling/Enabling of input fields and button when a certain button is clicked</summary>
SetEnable(false);
string connetionString;
SqlConnection cnn;
connetionString = #"Data Source=******\MSSQL****;Initial Catalog=*****;User ID=****;Password=****";
cnn = new SqlConnection(connetionString);
cnn.Open();
SqlCommand cmd = new SqlCommand("Update TV_LABCASE Set DEPARTMENT_CASE_NUMBER=#DEPARTMENT_CASE_NUMBER,DEPARTMENT_CODE=#DEPARTMENT_NAME,OFFENSE_CODE=#OFFENSE_DESCRIPTION,LAB_CASE=#LAB_CASE,OFFENSE_DATE=#OFFENSE_DATE where CASE_KEY=#CASE_KEY", cnn);
cmd.Parameters.AddWithValue("#DEPARTMENT_CASE_NUMBER", TextBox1.Text);
cmd.Parameters.AddWithValue("#DEPARTMENT_NAME", DropDownList1.SelectedValue);
cmd.Parameters.AddWithValue("#OFFENSE_DESCRIPTION", DropDownList2.SelectedValue);
cmd.Parameters.AddWithValue("#LAB_CASE", TextBox4.Text);
cmd.Parameters.AddWithValue("#OFFENSE_DATE", TextBox5.Text);
cmd.Parameters.AddWithValue("#CASE_KEY", TextBox6.Text);
cmd.ExecuteNonQuery();
cnn.Close();
TextBox7.Text = DropDownList1.SelectedItem.Text;
TextBox8.Text = DropDownList2.SelectedItem.Text;
GridView1.DataBind();
}
protected void btnCancel_Click(object sender, EventArgs e)
{ ///<summary> Disabling/Enabling of input fields and button when a certain button is clicked</summary>
SetEnable(false);
LoadData();
}
///<summary> Disabling/Enabling of input fields and button when a certain button is clicked</summary>
private void SetEnable(bool editable)
{
btnEdit.Enabled = !editable;
btnSave.Enabled = editable;
btnCancel.Enabled = editable;
TextBox1.Enabled = editable;
DropDownList1.Enabled = editable;
DropDownList2.Enabled = editable;
TextBox4.Enabled = editable;
TextBox5.Enabled = editable;
TextBox7.Visible = !editable;
TextBox8.Visible = !editable;
DropDownList1.Visible = editable;
DropDownList2.Visible = editable;
}
i'll just explained a while ago that i also have some issues in displaying the selected row value inside the dropdown, so instead of displaying inside the dropdown, I decided to put the value inside the textbox (which is why I included textbox 7 and 8 and they are only use to display the value of the selected row, after clicking edit button, it will be hidden and the dropdown will then be visible thus making effect of textbox turning into dropdown ) and hide and show them if i needed them. now the problem is that after I use the code you have given, the changes inside the textboxes wont save after clicking save button.

Extract code from your GridView1_RowCommand event handler into a seperate method like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Select")
{
//Convert the row index stored in the CommandArgument
//property to an Integer.
LoadData(Convert.ToInt32(e.CommandArgument));
}
}
//int? could be written as Nullable<int>
private void LoadData(int? rowNumber = null)
{
//if rowNumber is null use GridView1.SelectedIndex
var index = rowNumber ?? GridView1.SelectedIndex;
//instead of the ?? operator you can write a simple if
var index = -1;
if (rowNumber == null)
index = GridView1.SelectedIndex;
else
index = rowNumber.Value; //Access the value property of the nullable int
if (index == -1)
return; //index is invalid so exit the method
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = GridView1.Rows[index];
//Populate the input box with the value of selected row.
GridViewRow gr = GridView1.Rows[index];
TextBox1.Text = gr.Cells[2].Text;
//your code would add new Items to your DropDownList everytime this method gets called
//DropDownList1.Items.Add(gr.Cells[3].Text.ToString());
//DropDownList2.Items.Add(gr.Cells[4].Text.ToString());
//instead use SelectedItem property of the DropDownList, didn't know why you call .ToString() on the Text property, seemed redundant so I removed it
//DropDownList1.SelectedItem = gr.Cells[3].Text;
//DropDownList2.SelectedItem = gr.Cells[4].Text;
//as was pointed out in the comments below the SelectedItem is read-only for this control
//we need to use the following as is described here https://stackoverflow.com/questions/5121639
DropDownList1.Items.FindByText(gr.Cells[3].Text).Selected = true;
DropDownList2.Items.FindByText(gr.Cells[4].Text).Selected = true;
TextBox4.Text = gr.Cells[5].Text;
TextBox5.Text = gr.Cells[6].Text;
TextBox6.Text = gr.Cells[1].Text;
}
And in your event handler of your cancel button call the new method, like this:
protected void CancelButton_Click(object sender, EventArgs e)
{
LoadData();
}
FYI - the ///<summary> should only be used to desribe methods and not for in-line comments, for in-line comments stick to // comment syntax.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/xmldoc/summary

Related

Changing a gridview's datasource based on dropdownlist

I'm struggling a lot and I hope someone can help me please.
I have a 4 dropdownlists, a search button and a normal gridview with a basic SQLdataConnection.
The SQLdataConnection is a stored procedure that retrieves 3 tables based on 4 parameters. These 3 tables are then joined together into the gridview.
BUT
One of the dropdownlists has the options of Total, Fast and Slow. So based on which option the user chooses the respective table should be loaded into the gridview when the search button is pressed. (So if total is chosen, the total table should be loaded into the gridview)
I don't know if the SQLdataConnection should be changed with each option to show only the appropriate table.
Below is a copy of the html of the dropdowns and gridview as well as the code behind.
<tr>
<td style="text-align: right" class="pad-right-0">
<asp:DropDownList ID="selSeconds" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selHours" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selMerchantId" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:DropDownList ID="selTableType" runat="server" CssClass="selectbox select-chr" Visible="true"></asp:DropDownList>
<asp:Button ID="btnSearch" runat="server" CssClass="btn btn-primary btn-danger tip-s medium grey" ValidationGroup="Search" OnClick="btnSearch_Click" Text="<%$Resources:Resource, btnSearch %>" />
<asp:ImageButton ID="btnExportToExcel" runat="server" CssClass="btn btn-primary btn-danger tip-s medium grey" ValidationGroup="Search" onclick="btnExportToExcel_Click" Text="Export to excel" ImageUrl="images/Excel.png" AlternateText="<%$Resources:Resource, lblExportExcel %>"
CausesValidation="false" />
<asp:RequiredFieldValidator ID="rqrdMerchantId" runat="server" ErrorMessage="<%$Resources:Resource, lblRequired %>" ControlToValidate="selMerchantId" ForeColor="Red" />
</td>
</tr>
</table>
<asp:HiddenField ID="hdnMerchantId" runat="server" Value="0" />
<asp:GridView ID="gridSpeedAnalysis" runat="server" DataSourceID="gridSqlConnection">
</asp:GridView>
<asp:SqlDataSource ID="gridSqlConnection" runat="server"></asp:SqlDataSource>
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserName"] == null || Session["UserType"] == null)
{
Response.Redirect("Login.aspx");
}
LoadDropDowns();
}
private void LoadDropDowns()
{
System.Web.UI.WebControls.ListItem item;
selSeconds.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Select Second", "0"));
int index = 1;
for (int Second = 0; Second <= 10; Second++)
{
System.Web.UI.WebControls.ListItem li = new System.Web.UI.WebControls.ListItem(Second.ToString(), Second.ToString());
selSeconds.Items.Insert(index, li);
index++;
}
item = selSeconds.Items.FindByValue(DateTime.Now.Year.ToString());
selSeconds.SelectedIndex = selSeconds.Items.IndexOf(item);
if (Session["UserType"] != null && (Session["UserType"].ToString().ToLower() == "System Administrator".ToLower()))
{
selMerchantId.DataSource = BOL.MerchantGroup.Load();
selMerchantId.DataTextField = "Description";
selMerchantId.DataValueField = "MerchantId";
selMerchantId.DataBind();
selMerchantId.Items.Insert(0, new System.Web.UI.WebControls.ListItem { Value = "0", Text = "Select Group" });
rqrdMerchantId.InitialValue = "0";
}
else if (Session["UserType"].ToString().ToLower() == "Head Office".ToLower())
{
BOL.MerchantGroup group = new BOL.MerchantGroup(int.Parse(hdnMerchantId.Value));
selMerchantId.Items.Insert(0, new System.Web.UI.WebControls.ListItem { Value = hdnMerchantId.Value, Text = group.Description });
}
DataTable dt = BOL.Merchant.GetDropdownByMerhcantGroupId(int.Parse(Session["MerchantGroupId"].ToString()));
selMerchantId.DataSource = dt;
selMerchantId.DataTextField = "Name";
selMerchantId.DataValueField = "MerchantId";
selMerchantId.DataBind();
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Total"});
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Fast" });
selTableType.Items.Insert(0, new System.Web.UI.WebControls.ListItem {Text = "Slow" });
}
protected void btnSearch_Click(object sender, EventArgs e)
{
}

get selected value by drop down list in a repeater by CommandArgument of link button

I have a repeater that in it has one dropdown list and one linkbutton.
I want to get the selected value of the dropdown list by CommandArgument in linkbutton, but it just knows default value of dropdown list.
My code :
<asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="Page_Load2"OnItemCommand="list_ItemCommand" >
<ItemTemplate>
<asp:DropDownList ID="dlPricelist" CssClass="width100darsad dropdownlist" runat="server" AutoPostBack="true" ViewStateMode="Enabled" >
</asp:DropDownList>
<asp:LinkButton ID="btnAddToCart" runat="server" class="btn btn-success btnAddtoCardSinglepage" CommandArgument='<%#Eval("id") %>' CommandName="addtocard">اضافه به سبد خرید</asp:LinkButton>
<asp:Label ID="xxxxxx" runat="server" Text="Label"></asp:Label>
</ItemTemplate>
</asp:Repeater>
Code behind:
protected void Page_Load2(object sender, RepeaterItemEventArgs e)
{
if (!IsPostBack)
{
string id = Request.QueryString["id"].ToString();
DataSet dsselectcategory = BLLTour.left3join(id.Trim().ToString());
var dlPricelist = (DropDownList)e.Item.FindControl("dlPricelist");
dlPricelist.DataSource = dsselectcategory.Tables[0];
dlPricelist.DataTextField = "pricelistPrice";
dlPricelist.DataValueField = "priceid";
dlPricelist.DataBind();
}
}
protected void list_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "addtocard")
{
foreach (RepeaterItem dataItem in Repeater1.Items)
{
Label xxxxxx = (Label)e.Item.FindControl("xxxxxx");
LinkButton btnAddToCart = (LinkButton)e.Item.FindControl("btnAddToCart");
xxxxxx.Text = ((DropDownList)dataItem.FindControl("dlPricelist")).SelectedItem.Text; //No error
}
}
}
I don't know how I should fix it.
You are using very old technology to show data that's not appropriate.
But if you are serious to use it, you must use FindControll method in ItemTemplate of your repeater control. You should find dropdownlist first, and then cast it to a object to be able to use it's value.

How to fire an event when dropdown inside Repeater changes

I want to do some actions in my database when user change dropdown's selectedIndex.Now I have the following.
<td class="shop-item-qty">
<asp:DropDownList ID="qtyDropDownList" OnSelectedIndexChanged="changeCount" AutoPostBack="true" runat="server"/>
<asp:HiddenField ID="ItemId" runat="server" Value='<%#Eval("GiftVoucher.ID") %>'/>
</td>
All I want is to get my hidden fields value in changeCount method. The problem is that I can't directly get hidden fields value, because this code is in Repeater element. How can I achieve that functionality?
protected void qtyDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList control = (DropDownList)sender;
RepeaterItem rpItem = control.NamingContainer as RepeaterItem;
if (rpItem != null)
{
HiddenField hiddenField = ((HiddenField)rpItem.FindControl("ItemId"));
}
}
You can bind GiftVoucher.ID value to DropDown's custom attribute and skip HiddenField:
<asp:DropDownList runat="server" ID="qtyDropDownList" OnSelectedIndexChanged="changeCount" AutoPostBack="true" data-itemId='<%# Eval("ID") %>' />
protected void changeCount(object sender, EventArgs e)
{
var id = ((DropDownList)sender).Attributes["data-itemId"];
}

Buttons and repeater control

I am using ASP.NET, C#, Sql Server 2005 for my project and
I'm using the repeater control to form a table of users that are a member of a site and a button next to each user so that they can be added to your friends list. I have everything set up except I dont know how to get the specific info of each row after a button click. I mean,
How to send a friend request to a person whose username is displayed besides the button? or
How to access the the displayed username besides the button so that I can use it for my code?
My Script
<asp:Repeater ID="myrepeater" runat="server">
<HeaderTemplate>
<table style="font: 8pt verdana">
<tr style="background-color:#3C78C3">
<th>Search Result</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#DataBinder.Eval(Container,"DataItem.allun")%>
<asp:Button ID="Button1" runat="server" Text="Button" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
Code Behind
protected void btnSearch_Click(object sender, EventArgs e)
{
con.Open();
if (txtSearch.Text != "")
{
SqlDataAdapter mycommand = new SqlDataAdapter("select * from WebAdminTable where allun='" + txtSearch.Text + "'", con);
DataSet ds = new DataSet();
mycommand.Fill(ds);
myrepeater.DataSource = ds;
myrepeater.DataBind();
}
else
{
//msgbox for entering value
}
con.Close();
}
protected void btnAddToMyFList_Click(object sender, EventArgs e)
{
//?
}
You can bind the userName to a label control and then you can access the value of the label control on the click of button like...
protected void btnAddToMyFList_Click(object sender, EventArgs e)
{
Button btnAddToMyFList = (Button)sender;
Label label = (Label)btnAddToMyFList.Parent.FindControl("LabelId");
String labelText = label.Text; //userName of clicked row
}

Edit Textbox in Repeater

I have a repeater with a textbox inside. I am trying to edit the information inside the textbox, retrieve the new data, and write to the DB. With my code its giving me the original info that was in the box. Not the new information that I have added. Here is my code
html:
<asp:LinkButton id="saveReviewLinkButton" text="Save" runat="server" onCommand="saveReviewLinkButton_OnCommand" />
<table>
<asp:Repeater id="ReviewRepeater" runat="server" onItemDataBound="ReviewRepeater_ItemDataBound">
<itemtemplate>
<tr >
<td ><asp:TextBox id="titleLabel" runat="server" width="200px" textMode="MultiLine"/></td>
</tr>
</itemtemplate>
</table>
c#:
protected void ReviewRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
Review review = (Review)e.Item.DataItem;
TextBox titleLabel = (TextBox)e.Item.FindControl("titleLabel");
titleLabel.Text = review.Title;
}
}
protected void saveReviewLinkButton_OnCommand(object sender, EventArgs e)
{
TextBox titleLabel = new TextBox();
foreach (RepeaterItem dataItem in ReviewRepeater.Items)
{
titleLabel = (TextBox)dataItem.FindControl("titleLabel");
string newInfo = titleLabel.Text;
}
}
Please make sure, you are binding the data to the repeater by checking in page load
if(!IsPostBack)
BindData();

Categories

Resources