Buttons and repeater control - c#

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
}

Related

Disregard Changes in input fields/dropdown using ASP.NET 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

Bind RadiobuttonList inside DataList

Good morning .
I search many times before posting here .
I am working on a project like a survey [Questions and Answers]
I am able to get all questions in datalist , now i am searching a way to display the answers in Radio button list inside each question .
here is page load
protected void Page_Load(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["TMConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
//Getting All Questions
SqlDataAdapter dr = new SqlDataAdapter("select * from Question ", con);
DataSet ds = new DataSet();
dr.Fill(ds, "Qs");
OuterDataList.DataSource = ds.Tables["Qs"];
OuterDataList.DataBind();
}
here is page body
<body>
<form id="form1" runat="server">
<h1>Test Page</h1>
<asp:DataList ID="OuterDataList" RunAt="server">
<ItemTemplate>
<h4><%# DataBinder.Eval (Container.DataItem, "Question") %></h4>
<asp:RadioButtonList ID="RadioButtonList1" runat="server"></asp:RadioButtonList>
</ItemTemplate>
</asp:DataList>
</form>
i dont know how to bind radiobuttonlist and group the answers .
note : the common column between Question table and Answer table is Question_id
Firt will make a template like below.
<asp:DataList runat="server" ID="DataList1" RepeatDirection="Vertical"
DataKeyField="QuestionID" onitemdatabound="DataList1_ItemDataBound">
<ItemTemplate>
<table>
<tr>
<td>
<%# Eval("Question") %>
</td>
</tr>
<tr>
<td>
<asp:RadioButtonList runat="server" ID="RadioButtonList1">
</asp:RadioButtonList>
</td>
</tr>
</table>
</ItemTemplate>
After that using DataList1_ItemDataBound you can bind your answers.
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
RadioButtonList RadioButtonList1 = (RadioButtonList)e.Item.FindControl("RadioButtonList1");
//Get questionID here
int QuestionID = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "QuestionID"));
//pass Question ID to your DB and get all available options for the question
//Bind the RadiobUttonList here
}
}

Asp.Net / C# - How to get the Text of a Label control nested inside a Repeater?

I am trying to get the text of my label which is inside a repeater, but I keep getting a NullPointerException.
All of the data is coming from database and it is coming correctly.
When I click on the LinkButton, I want to use the Label Text for next bit code.
Aspx page:
<asp:Repeater ID="RepeaterDepartmentParent" runat="server">
<ItemTemplate>
<div id="outerDiv" class="col-lg-3 col-xs-6" runat="server">
<!-- small box -->
<div>
<div class="inner">
<p>
<%# DataBinder.Eval(Container.DataItem, "Department_Namestr")%>
</p>
</div>
<asp:Label ID="lblDepartmentId" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Department_Idint")%>' Visible="true"></asp:Label>
<asp:LinkButton ID="linkChildDepartment" CommandName="Click" runat="server" CssClass="small-box-footer" OnClick="linkChildDepartment_Click">More info<i class="fa fa-arrow-circle-right"></i></asp:LinkButton>
</div>
</div><%--<%-- ./col -->--%>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
DataSet dsParentDepartment = null;
dsParentDepartment = objDepartmentBL.viewDepartmentparent();
RepeaterDepartmentParent.DataSource = dsParentDepartment.Tables[0];
RepeaterDepartmentParent.DataBind();
}
protected void linkChildDepartment_Click(Object sender, EventArgs e)
{
//what to write here??
//i have tried the bellow code but it gives me every data in that loop but i
//want the single data for a link button click.
//foreach (RepeaterItem item in RepeaterDepartmentParent.Items)
// {
// Label myLabel = (Label)item.FindControl("lblDepartmentId");
// myLabel.Text = Id;
//}
//edited code that works properly
LinkButton linkChildDepartment = (LinkButton)sender;
RepeaterItem item = (RepeaterItem)linkChildDepartment.NamingContainer;
Label myLabel = (Label)item.FindControl("lblDepartmentId");
}
How can I correctly reference the Link Button Label Text?
You can use the NamingContainer property to get the reference of the RepeaterItem. From there it's a short way to your label:
protected void linkChildDepartment_Click(Object sender, EventArgs e)
{
LinkButton linkChildDepartment = (LinkButton) sender;
RepeaterItem item = (RepeaterItem) linkChildDepartment.NamingContainer;
Label myLabel = (Label)item.FindControl("lblDepartmentId");
// ...
}

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();

Error when dropdownlist.databind() if I change from FormView.EditMode to FormView.InsertMode

I have a FormView like:
<EditItemTemplate>
<th>Test Name</td>
<td><asp:Label runat="server" ID="lblSuite" Text='<%# Eval("Suite") %>'></asp:Label></td>
</EditItemTemplate>
<InsertItemTemplate>
<th>Test Name</td>
<td><asp:DropDownList ID="insertSuite" runat="server"></asp:DropDownList></td>
</InsertItemTemplate>
Which means in InsertMode, the user can change Suite using a dropdownlist while in EditMode, the user can only see Suite but cannot do modification.
If the user click one of the record, FormView was changed into EditMode with the code:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//getDatasource
FormView1.DataSource = objList;
FormView1.ChangeMode(FormViewMode.Edit);
FormView1.DataBind();
}
If the user click the Add New button, FormView was changed into InsertMode with the code:
FormView1.ChangeMode(FormViewMode.Insert);
protected void btnAddSingle_Click(object sender, EventArgs e)
{
FormView1.ChangeMode(FormViewMode.Insert);
DropDownList drp = (DropDownList)FormView1.FindControl("insertSuite");
drp.DataSource = otherRepo.SuiteDropdownListDataSource(2);
drp.DataTextField = "Name";
drp.DataValueField = "Name";
drp.DataBind();
}
My Problem is:
If I click the one of the record and get into EditMOde, Then click the Add New button, Then error occured.
the (DropDownList)FormView1.FindControl("insertSuite") is null.
I thought it was something about lifecycle but cannot figure it out.
You have to DataBind the FormView after you've called ChangeMode and before FormView1.FindControl.
So this works:
FormView1.ChangeMode(FormViewMode.Insert);
FormView1.DataBind();
DropDownList drp = (DropDownList)FormView1.FindControl("insertSuite");

Categories

Resources