Bind a HiddenField within a gridview - c#

I want to bind a Hidden Field because I want to pass a value from code behind to the asp:Parameter Name="HOME_TEAM_COACH_ID" Type="Int32".
My asp:
<asp:FormView ID="FormView1" runat="server" OnItemUpdated="FormView1_ItemUpdating" >
<EditItemTemplate>
HOME_TEAM:
<asp:DropDownList ID="DropDownListHometeam" runat="server"
DataSourceID="SqlDataGetTeams"
DataTextField="NAME" DataValueField="ID" SelectedValue='<%# Bind("HOME_TEAM_ID") %>'>
</asp:DropDownList>
<asp:HiddenField runat="server" ID="testLabel" Value='<%# Bind("HOME_TEAM_COACH_ID") %>' />
</EditItemTemplate>
And c# behind is:
protected void FormView1_ItemUpdating(object sender, FormViewUpdatedEventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Edit)
{
DropDownList HomeTeamId = FormView1.FindControl("DropDownListHometeam") as DropDownList;
string team = string.Format("{0}", HomeTeamId.Text);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BasketballConnectionString1"].ToString());
conn.Open();
string queryHome = "SELECT dbo.COACH.ID, dbo.COACH.SURENAME FROM dbo.COACH INNER JOIN dbo.GAMES ON dbo.COACH.TEAM_ID = dbo.GAMES.HOME_TEAM_ID WHERE (dbo.GAMES.HOME_TEAM_ID =" + team + ")";
SqlCommand cmd = new SqlCommand(queryHome, conn);
var Home_Coach_Id = cmd.ExecuteScalar().ToString();
HiddenField HomeCoachIdLabel = FormView1.FindControl("testLabel") as HiddenField;
HomeCoachIdLabel.Value = Convert.ToString(Home_Coach_Id);
conn.Close();
I want Help with the last four lines where I want to pass the Home_Coach_Id value to bind the asp:HiddenField ID="testLabel" Value='<%# Bind("HOME_TEAM_COACH_ID") %>'.
When I click update, it doesn't change the value in database. (When I debug, in the last lines it gives me the correct HomeCoachIdLabel.Value.)
any suggestions?

You do not need the explicitly set the HiddenField's Value property, because it is done by the <%# Bind("HOME_TEAM_COACH_ID") %> in your markup.
I believe your problem is that you are not returning the HOME_TEAM_COACH_ID from your query to the database in your SELECT statement:
SELECT dbo.COACH.ID, dbo.COACH.SURENAME FROM dbo.COACH
INNER JOIN dbo.GAMES ON dbo.COACH.TEAM_ID = dbo.GAMES.HOME_TEAM_ID
WHERE (dbo.GAMES.HOME_TEAM_ID =" + team + ")

The problem is that it needs the method prerender and not the method onitemupdated.
asp:FormView ID="FormView1" runat="server" OnPreRender="FormView1_OnPreRender" >
and also in c#
protected void FormView1_OnPreRender(object sender, FormViewUpdatedEventArgs e)
{
It also works when I put it in page load{ }.
The next step is to make the insert event....

Related

LinkButton OnClick within a Nested Repeater

I am having trouble with a LinkButton firing the OnClick event where the LinkButton is in a nested repeater.
Here is my HTML Markup
<asp:Repeater ID="RepeaterGenres" runat="server" OnItemDataBound="LoadTitles">
<ItemTemplate>
<asp:HiddenField ID="hdnGenre" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "GenreID") %>' />
<%# DataBinder.Eval(Container.DataItem, "MovieGenre") %>
<asp:Repeater ID="RepeaterMovies" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "MovieName") %>
<asp:LinkButton ID="lbMovieInfo" runat="server" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "MovieID") %>' OnClick="LoadMovieTitle">
Access Info
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
Here is my method to load the Genres. (have removed some of the declarations to simplify).
string sqlString = "SELECT * FROM Movies_Genres";
sqlCmd = new SqlCommand(sqlString, myConnection);
sqlReader = sqlCmd.ExecuteReader();
if (sqlReader.HasRows)
{
RepeaterGenres.DataSource = sqlReader;
RepeaterGenres.DataBind();
}
Here is my method to load the Movie Titles within each Genre.
protected void LoadTitles(object sender, RepeaterItemEventArgs args)
{
if (args.Item.ItemType == ListItemType.Item || args.Item.ItemType == ListItemType.AlternatingItem)
{
// Genre from HiddenField
HiddenField GenreID = (HiddenField)args.Item.FindControl("hdnGenre");
// Repeater
Repeater childRepeater = (Repeater)args.Item.FindControl("RepeaterMovies");
string sqlString = "SELECT * FROM Movies_Titles " +
"WHERE Genre = #Genre";
sqlCmd = new SqlCommand(sqlString, myConnection);
sqlCmd.Parameters.AddWithValue("#Genre", GenreID.Value);
sqlReader = sqlCmd.ExecuteReader();
if (sqlReader.HasRows)
{
childRepeater.DataSource = sqlReader;
childRepeater.DataBind();
}
else
{
childRepeater.DataSource = "";
childRepeater.DataBind();
}
}
}
Everything up to this point works fine. I get my Genre groups and within each Genre I get the movie titles that are flagged against that Genre, and also the Linkbutton against each movie title. It's the LinkButton that is NOT firing the OnClick event.
Here is the code i'm using for the OnClick event.
protected void LoadMovieTitle (Object sender, EventArgs e)
{
LinkButton linkb = (LinkButton)(sender);
string args = linkb.CommandArgument;
Response.Redirect("movieinfopage.aspx?id=" + args);
}
The solution I am hoping to get help with is what do I need to do in order for those LinkButtons to fire their OnClick event when clicked, and access LoadMovieTitle. When I put a break in this method, it does not break, telling me that the OnClick event is not finding or recognising it.
You need to add OnItemCommand to repeater and CommandName to LinkButton:
<asp:Repeater ID="RepeaterMovies" runat="server" OnItemCommand="RepeaterMovies_OnItemCommand">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "MovieName") %>
<asp:LinkButton ID="lbMovieInfo" runat="server" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "MovieID") %>' CommandName="MovieDetail">
Access Info
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
Server side:
protected void RepeaterMovies_OnItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName.Equals("MovieDetail"))
{
LinkButton linkb = (LinkButton)(sender);
string args = linkb.CommandArgument;
Response.Redirect("movieinfopage.aspx?id=" + args);
}
}
See:
https://learn.microsoft.com/en-us/aspnet/web-forms/overview/data-access/custom-button-actions-with-the-datalist-and-repeater/custom-buttons-in-the-datalist-and-repeater-cs

How do I show an associated value with a dropdown list item (after choosing it from the list)?

I am programming in ASP.NET, visual studio. I have a dropdown list created in HTML form. If I dropdown the list, it displays the record from associated column in the table. But what I want is to show the corresponding value / record with that list item.
For example in the table, I have column id, productname and price. After choosing a particular product name (from drop down list), the associated price with it must be displayed in front of it (in a label).
However, By default, I want the drop down list to shows nothing in the beginning.
UPDATE:
Store.aspx:
<form id="form1" runat="server">
<div>
Welcome
<asp:Label ID="Label3" runat="server" ></asp:Label>
<br />
<br />
Products: <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" ></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [productdata]"></asp:SqlDataSource>
Price:
<asp:Label ID="Label1" runat="server" ></asp:Label>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Add to Cart" />
<br />
<br />
Items in cart: <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
<br />
<br />
Total Price: <asp:Label ID="Label2" runat="server"></asp:Label>
</div>
</form>
Store.aspx.cs:
public partial class Store : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label3.Text = Request.QueryString["name"];//show welcome text
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
if (!IsPostBack)
{
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata", sc);
sc.Open();
DropDownList1.DataTextField = "productname";//show in the dropdown list
DropDownList1.DataValueField = "price"; //show in the label
DropDownList1.DataSource = sqlcom.ExecuteReader();
DropDownList1.DataBind();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlDataReader rd;
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata where id=" + Convert.ToUInt32(DropDownList1.SelectedValue), sc);
sc.Open();
rd = sqlcom.ExecuteReader();
if (rd.Read())
{
Label1.Text = rd[2].ToString();
}
sc.Close();
}
}
}
Database:
CREATE TABLE [dbo].[productdata] (
[Id] INT NOT NULL,
[productname] VARCHAR (50) NULL,
[price] FLOAT (53) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
This Edit according to using AutoPostBack=True and if (!IsPostBack) in Page_Load thanks to Arindam:
For simply solution using postback event:
First you should add OnSelectedIndexChanged event for dropdownlist
<asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="GetPrice" AutoPostBack="true">
</asp:DropDownList>
Then in code behind you just get selected value and fill to the label price
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label3.Text = Request.QueryString["name"];//show welcome text
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata", sc);
sc.Open();
DropDownList1.DataTextField = "productname";//show in the dropdown list
DropDownList1.DataValueField = "price"; //show in the label
DropDownList1.DataSource = sqlcom.ExecuteReader();
DropDownList1.DataBind();
}
}
}
protected void GetPrice(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedValue;
}
You have to use AutoPostBack=True so that when you change index of dropdownlist, it will trigger a postback to server so the function GetPrice(...) will be called.
Every time the page postback, it will call function Page_Load(...) first, so you must use propertive IsPostBack to check if case1_this is the first time the page is loaded, or case2_a postback event, and you only set the ddl datasource at case1 because if you set datasource, by default the dropdownlist will reset to select first item in list.
When you go advance, you should consider using Javascript and Jquery to solve this, so the page will not load again like this postback solution.
And one more thing, you should name your controls well, don't make them default like that. It's one of two hard things in programming.
Yes you can but if not please use datatable and i am sure that work fine .if u not able do that just post I will give the correction.

SelectIndex_changed not worling in Asp.net for selecting values

i am new on .net development now i am facing the problem but i do not know what the solution for this
i am creating the dropdown list and bind it with data but when i select the any data from list it does not changes the textbox with the related value but when i click on button it goes inside the code means goes on debuging from where i mark the debug cursor
here is my code behind
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCardCode = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("Data Source=testing;Initial Catalog=testdb;Persist Security Info=True;User ID=abcd;Password=asdfg");
using (connection)
{
SqlCommand theCommand = new SqlCommand("SELECT T1.CardCode , T1.CardName,T3.CntctCode,T3.Name FROM OCRD T1 inner join OCPR T3 on T1.CardCode=T3.CardCode where T3.CardCode=#CardCode ", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selectedCardCode);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
this.TextBox1.Text = theReader["CardCode"].ToString();
this.TextBox2.Text = theReader["CardName"].ToString();
this.DropDownList1.SelectedItem.Value = selectedCardCode;
}
connection.Close();
}
}
and here is my method cardcode
protected void LoadOptionsCardCodeTable()
{
DataTable CardCode = new DataTable();
string id, name, newName;
SqlConnection connection = new SqlConnection("Data Source=abc;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=asdf;Password=asdfgh");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT T1.CardCode , T1.CardName from ocrd T1 ", connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = name + " ---- " + id;
DropDownList1.Items.Add(new ListItem(newName, id));
}
}
}
}
here is my design code
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server"
ondatabinding="DropDownList1_SelectedIndexChanged"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" ontextchanged="TextBox2_TextChanged"></asp:TextBox>
</form>
Kindly help your help will be higly appreciatable
Set AutoPostBack property to true for your dropdownlist.
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
ondatabinding="DropDownList1_SelectedIndexChanged"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
By default, asp.net server controls like dropdownlist, textbox have their respective events as cached which means it registers the event but does not fire untill an actual postback happens. In you case when you are clicking the button a postback is happening and the cached event of your dropdwonlist is also getting executed.
To force postback from your dropdown you will have to set the PostBack property to true.
You have to set AutoPostBack="true" in order to trigger the event:
<asp:DropDownList ID="DropDownList1" runat="server"
ondatabinding="DropDownList1_SelectedIndexChanged"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
Notes:
A postback is initiated by the browser, and reloads the whole page, according to an event.if any changes(here onselectedindexchanged) we made in the control result in a postback then that are called AutoPostBack.All controls except, Buttons, Hyperlinks and LinkButtons have a default AutoPostBack property of false, we have an option to make them true if needed.
Set AutoPostBack="true" Otherwise DropDownList1_SelectedIndexChanged doesn't fire.
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
ondatabinding="DropDownList1_SelectedIndexChanged"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>

DataList not displaying data

So I have a DataSource and also a DataList:
<asp:SqlDataSource ID="SearchDataSource" runat="server"
ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\4WheelsDB.mdb;Persist Security Info=True"
ProviderName="System.Data.OleDb">
</asp:SqlDataSource>
<asp:DataList ID="DataList1" runat="server" DataSourceID="SearchDataSource"></asp:DataList>
When a user clicks on a button it performs this code which amends the query according to what the user has chosen:
query = "SELECT * FROM Cars WHERE "
if(make != 1)
{
query = query + "make_id = #make";
SearchDataSource.SelectParameters.Add("make", make.ToString());
}
SearchDataSource.SelectCommand = query;
btn_search.Text = DataList1.Items.Count.ToString();
However when the datalist should show some rows the btn_search.Text displays 0 and rows are not shown in the datalist, does anyone know what I am doing wrong?
You should add where clause in your query.
C#
query = "SELECT * FROM Cars"
if(make != 1)
{
query = query + " where make_id = #make"; // add here
SearchDataSource.SelectParameters.Add("make", make.ToString());
}
SearchDataSource.SelectCommand = query;
btn_search.Text = DataList1.Items.Count.ToString();
ASPX
<asp:DataList ID="DataList1" runat="server" DataSourceID="SearchDataSource">
<ItemTemplate>
<asp:Label ID="lblmake_id" runat="server" Text='<%# Eval("make_id")%>' />
</ItemTemplate>
</asp:DataList>

Cannot get textbox value from textbox in itemtemplate

The quantity (quantityWanted in DB) in textbox is loaded via Eval() method from Basket DB table. What I want to achieve is that when I change quantity manually and click update the quantity for that record will be updated and then grid will be reloaded. I seem unable to retrieve value of that textbox in code behind.
I am aware of FindControl() method which is used to get value from controls within itemtemplate but I don't know how to use it here.
The tried below but always get nullReferenceException
TextBox txt = (TextBox)GridView2.FindControl("txtQuantityWanted");
int _quantity = Convert.ToInt16(txt.Text);
Note: button is there but does nothing.
<ItemTemplate>
<asp:TextBox runat="server" ID="txtQuantityWanted" Text='<%# Eval("quantityWanted") %>' ></asp:TextBox>
<asp:LinkButton ID="LinkButton11" runat="server" CommandName="update" CommandArgument='<%# Eval("coffeeName") + ";" + Eval("datetimeAdded") %>' >Update</asp:LinkButton>
<asp:Button ID="Button21" runat="server" Text="Button" CommandName="edit" />
</ItemTemplate>
<asp:TemplateField HeaderText="Total [£]">
<ItemTemplate>
<asp:Label id="lblItemTotal" runat="server" Text='<%# String.Format("{0:C}", Convert.ToInt32(Eval("quantityWanted"))* Convert.ToDouble(Eval("price"))) %>' ></asp:Label>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="remove" CommandArgument='<%# Eval("coffeeName") + ";" + Eval("datetimeAdded") %>' >Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
C# code:
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
// .....
else if (e.CommandName == "update")
{
string params = Convert.ToString(e.CommandArgument);
string[] arg = new string[2];
arg = params.Split(';');
name = Convert.ToString(arg[0]);
datetimeAdded = Convert.ToString(arg[1]);
const string strConn = #"Data Source=.\SQLEXPRESS;AttachDbFilename=L:\ASP.NET\Exercise1\Exercise1\Exercise1\App_Data\ASPNETDB.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
DataSet ds = new DataSet("Employees");
SqlConnection connection = new SqlConnection(strConn);
// Here I need value from textbox to replace 11
SqlCommand abc = new SqlCommand("UPDATE Basket SET quantityWanted = 11 WHERE coffeeName LIKE '%" + name + "%' AND datetimeAdded LIKE '" + datetimeAdded + "' ", connection);
connection.Open();
int ii = abc.ExecuteNonQuery();
connection.Close();
}
}
Use GridView.Rows collection to find control. You can pass the index of row in rows collection indexer.
TextBox txt = (TextBox)GridView2.Rows[0].FindControl("txtQuantityWanted");
You must pass the row index as well,Your code will look like this
TextBox txt = (TextBox)GridView2.Rows[0].FindControl("txtQuantityWanted");
I hope it will work for you.
Control ctrl = e.CommandSource as Control;
if (ctrl != null)
{
GridViewRow gvRow = ctrl.Parent.NamingContainer as GridViewRow;
TextBox txt= (TextBox)gvRow.FindControl("txtQuantityWanted");
}

Categories

Resources