Asp.net button not working - c#

When I click the button the information doesn't load into my table.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="frmManageUsers.aspx.cs" Inherits="frmManageUsers" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div align="center">
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="~/images/CoolBiz_Productions_logo.JPG" PostBackUrl="~/frmMain.aspx" />
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT [UserID], [UserName], [UserPassword], [SecurityLevel] FROM [tblUserLogin]">
</asp:SqlDataSource>
</div>
<div align="center">
<asp:Label ID="Label1" runat="server" Text="Manage Users"></asp:Label>
<p>
<asp:Label ID="Label2" runat="server" Text="User Name:"></asp:Label>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</p>
<p>
<asp:Label ID="Label3" runat="server" Text="Password:"></asp:Label>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</p>
<p>
<asp:Label ID="Label4" runat="server" Text="Security Level:"></asp:Label>
<asp:DropDownList ID="drpdwnlstSecurityLevel" runat="server"
onselectedindexchanged="drpdwnlstSecurityLevel_SelectedIndexChanged">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>U</asp:ListItem>
</asp:DropDownList>
</p>
<p>
<asp:Button ID="btnAddUser" runat="server" Text="Add User"
onclick="btnAddUser_Click1" />
</p>
<p>
<asp:Label ID="lblError" runat="server"></asp:Label>
</p>
</div>
<p>
</p>
<div align="center">
<asp:GridView ID="tblUserLogin" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" InsertVisible="False"
SortExpression="UserID"></asp:BoundField>
<asp:BoundField DataField="UserName" HeaderText="UserName"
SortExpression="UserName"></asp:BoundField>
<asp:BoundField DataField="UserPassword" HeaderText="UserPassword"
SortExpression="UserPassword"></asp:BoundField>
<asp:BoundField DataField="SecurityLevel" HeaderText="SecurityLevel"
SortExpression="SecurityLevel"></asp:BoundField>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
Here is my code for frmManageUsers
public partial class frmManageUsers : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAddUser_Click1(object sender, EventArgs e)
{
//string userName, userPassword;
if (txtUserName.Text == "" || txtUserName.Text == null)
{
lblError.Text = ("User Name may not be empty");
lblError.ForeColor = System.Drawing.Color.Red;
return;
}
// else
// userName = (txtUserName.Text);
if (txtPassword.Text == "" || txtPassword.Text == null)
{
lblError.Text = ("Password may not be empty");
lblError.ForeColor = System.Drawing.Color.Red;
return;
}
//else
// userPassword = (txtPassword.Text);
Session["UserName"] = txtUserName.Text;
Session["Password"] = txtPassword.Text;
Session["SecurityLevel"] = drpdwnlstSecurityLevel.SelectedValue;
Server.Transfer("frmManageUsers.aspx");
//Server.Transfer("grdUserLogin");
}
protected void drpdwnlstSecurityLevel_SelectedIndexChanged(object sender, EventArgs e)
{
}
}

You're SQL DataSource is tied to your DATAGRID control only. I don't see where in your btnAddUser_Click1 event handler you are making any calls to insert the record into the database. You will need to add this missing logic as the existing controls aren't wired up to do this. You have a code gap. You're going to need to perform something close to the following. This is just a sample as I pulled it out of one of my data access layers and modified it for viewing purposes.
string _connectionString = string.Empty;
SqlCommand sqlCommand = new SqlCommand();
SqlConnection sqlConnection = new SqlConnection();
._connectionString = config["connectionString"];
sqlConnection.ConnectionString = "<your connection string>";
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.StoredProcedure;
//add your parameters here
sqlCommand.Parameters.Add("#ParameterNameWithinProcedure", <your value goes here>);
sqlCommand.Parameters.Add("#ParameterNameWithinProcedure", <your value goes here>);
sqlCommand.Parameters.Add("#ParameterNameWithinProcedure", <your value goes here>);
//Repeat for each parameter in your record.
int returnVal = 0;
sqlCommand.CommandText = "< insert record stored procedure name"
try
{
sqlConnection.Open();
using (sqlCommand)
{
returnVal = sqlCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//possibly put some logging inforaation here
}
finally
{
sqlConnection.Close();
}
PS. In your if statements such as:
if (txtUserName.Text == "" || txtUserName.Text == null){//....}
Try using
if(String.IsNullOrEmpty(txtUserName.Text)){//...}
It's a nifty little method that reduces code.

Related

How do i pass a command argument of a button in Data List to another page?

Actually i am trying to redirect command argument of a button present in a data list to another page. I am using Request.QueryString method to access the command argument on another page with the help of command name of the button. Please help me with it...
this is code of button present inside Data List
<asp:Button ID="Button1" runat="server" Text="Read" CommandArgument='<%# Eval("id")%>' OnClick="Button1_Click" CommandName="content"/>
this is code present in DataList Item command function
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
Response.Redirect("content.aspx?content=" +e.CommandArgument.ToString());
}
this is the onclick function code
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("content.aspx");
}
this is the code on another page(content.aspx)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String id = Request.QueryString["content"];
Label1.Text = id;
}
}
this is entire datalist code
<asp:DataList ID="DataList1" runat="server" DataKeyField="Id" DataSourceID="SqlDataSource1" Height="657px" RepeatColumns="4" RepeatDirection="Horizontal" Width="1248px" OnItemCommand="DataList1_ItemCommand" OnItemDataBound="DataList1_ItemDataBound">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<ItemStyle ForeColor="#000066" />
<ItemTemplate>
<table class="auto-style2">
<tr>
<td style="text-align: center">
<asp:Label ID="Label2" runat="server" Text='<%# Eval("name") %>'></asp:Label>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Id") %>' Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Image ID="Image2" runat="server" Height="250px" ImageUrl='<%# Eval("image") %>' Width="250px" />
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<br />
<asp:ImageButton ID="ImageButton1" runat="server" CommandName="addtofav" CommandArgument='<%# Eval("id")%>' Height="30px" Width="20px" />
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Button ID="Button1" runat="server" Text="Read" CommandArgument='<%# Eval("id")%>' OnClick="Button1_Click" CommandName="content"/>
</td>
</tr>
</table
<br />
<br />
</ItemTemplate>
<SelectedItemStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
it does redirect to another page(content.aspx) but the label does not show the querystring text.
Try updating the DataList1_ItemCommand event to this:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "content")
{
Response.Redirect("content.aspx?content=" +e.CommandArgument.ToString());
}
}
also make sure you are checking IsPostBack in Page_Load method of this page code behind.
Yes i got the desired output. Actually i was also using another button to redirect to a diiferent page in DataList1_ItemCommand function. So i just needed to seperate the Response.redirects of the 2 buttons by putting them in if loop.
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "content")
{
Response.Redirect("content.aspx?content="+e.CommandArgument.ToString());
}
if (e.CommandName == "addtofav")
{
Response.Redirect("sortbyAZ.aspx?addtofav=" + e.CommandArgument.ToString());
}
}
Thanks You everybody for helping me out with this one
I think you are not casting the Request.QueryString["content"] to string format, try this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String id = Request.QueryString["content"];
Label1.Text = id;
}
}
You can find all information you need in this tutorial. from #microsoft msdn
Best of luck
<%# Page Language="C#" AutoEventWireup="True" %>
<%# Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>DataList Select Example</title>
<script runat="server">
ICollection CreateDataSource()
{
// Create sample data for the DataList control.
DataTable dt = new DataTable();
DataRow dr;
// Define the columns of the table.
dt.Columns.Add(new DataColumn("Item", typeof(Int32)));
dt.Columns.Add(new DataColumn("Qty", typeof(Int32)));
dt.Columns.Add(new DataColumn("Price", typeof(double)));
// Populate the table with sample values.
for (int i = 0; i < 9; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i * 2;
dr[2] = 1.23 * (i + 1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
void Page_Load(Object sender, EventArgs e)
{
// Load sample data only once, when the page is first loaded.
if (!IsPostBack)
{
ItemsList.DataSource = CreateDataSource();
ItemsList.DataBind();
}
}
void Item_Command(Object sender, DataListCommandEventArgs e)
{
// Set the SelectedIndex property to select an item in the DataList.
ItemsList.SelectedIndex = e.Item.ItemIndex;
// Rebind the data source to the DataList to refresh the control.
ItemsList.DataSource = CreateDataSource();
ItemsList.DataBind();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<h3>DataList Select Example</h3>
Click <b>Select</b> to select an item.
<br /><br />
<asp:DataList id="ItemsList"
GridLines="Both"
CellPadding="3"
CellSpacing="0"
OnItemCommand="Item_Command"
runat="server">
<HeaderStyle BackColor="#aaaadd">
</HeaderStyle>
<AlternatingItemStyle BackColor="Gainsboro">
</AlternatingItemStyle>
<SelectedItemStyle BackColor="Yellow">
</SelectedItemStyle>
<HeaderTemplate>
Items
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton id="SelectButton"
Text="Select"
CommandName="Select"
runat="server"/>
Item <%# DataBinder.Eval(Container.DataItem, "Item") %>
</ItemTemplate>
<SelectedItemTemplate>
Item:
<asp:Label id="ItemLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Item") %>'
runat="server"/>
<br />
Quantity:
<asp:Label id="QtyLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Qty") %>'
runat="server"/>
<br />
Price:
<asp:Label id="PriceLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}")
%>'
runat="server"/>
</SelectedItemTemplate>
</asp:DataList>
</form>
</body>
</html>
By the way I think you don't need define Button Click event. Already defined path with variable. Just convert button to Link Button and remove Button Click Event

Static DropDownList in DataGrid returns wrong selected value after button click event C# ASP.NET

I want to grab the selected value from the DropDownLists in my DataGrid when a submit button is clicked, but they always return the first option in the dropdown (approve). How can I get the selected value when using static dropdown items like this?
.aspx code:
<!-- several BoundColumns were here -->
<asp:TemplateColumn HeaderText="Actions">
<HeaderStyle CssClass="ProfDataGridHeader" BorderStyle="Solid" BorderWidth="1"></HeaderStyle>
<ItemStyle Width="45%" CssClass="ProfDataGridRow" BorderStyle="Solid" BorderWidth="1"></ItemStyle>
<ItemTemplate>
<asp:DropDownList ID="ddlApprovalStatus" AppendDataBoundItems="True" runat="server" Width="150px" EnableViewState="true" ViewStateMode="Enabled">
<asp:ListItem Value="approve" Text="Approve"></asp:ListItem>
<asp:ListItem Value="reject" Text="Reject"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" CssClass="ally-btn" OnClick="btnSubmit_Click" />
.aspx.cs code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
DropDownList DDLP;
string acceptStatus;
debugLabel.Text = "";
for (int i = 0; i < dgApprovals.Items.Count; i++)
{
DDLP = (DropDownList)dgApprovals.Items[i].FindControl("ddlApprovalStatus");
acceptStatus = DDLP.SelectedValue;
debugLabel.Text += acceptStatus + ", ";
}
}
The debugLabel.Text always ends up being "accept, accept, accept..." even when the DropDownLists have "Reject" selected.
Reproduced and fixed your problem by handling post-back events.
default.aspx.cs
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace DropdownClicks
{
public partial class WebForm1 : System.Web.UI.Page
{
static List<string> itemsToInsert = new List<string> { "first", "second", "third" };
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//only do this binding on page load, otherwise you'll "reset" the grid every time there is a postBack.
mydg.DataSource = itemsToInsert;
mydg.DataBind();
}
}
protected void Unnamed_Click(object sender, EventArgs e)
{
DropDownList DDLP;
string acceptStatus;
string retVal = "";
for (int i = 0; i < mydg.Items.Count; i++)
{
DDLP = (DropDownList)mydg.Items[i].FindControl("ddlApprovalStatus");
acceptStatus = DDLP.SelectedValue;
retVal += acceptStatus + ", ";
}
lbl_1.Text = retVal;
}
}
}
default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DropdownClicks.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label Text="text" runat="server" ID="lbl_1" />
<asp:DataGrid runat="server" ID="mydg" EnableViewState="true">
<Columns>
<asp:TemplateColumn HeaderText="Actions">
<HeaderStyle CssClass="ProfDataGridHeader" BorderStyle="Solid" BorderWidth="1"></HeaderStyle>
<ItemStyle Width="45%" CssClass="ProfDataGridRow" BorderStyle="Solid" BorderWidth="1"></ItemStyle>
<ItemTemplate>
<asp:DropDownList ID="ddlApprovalStatus" AppendDataBoundItems="True" runat="server" Width="150px" EnableViewState="true" ViewStateMode="Enabled">
<asp:ListItem Value="approve" Text="Approve"></asp:ListItem>
<asp:ListItem Value="reject" Text="Reject"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:Button Text="click me" runat="server" OnClick="Unnamed_Click" EnableViewState="true" />
</div>
</form>
</body>
</html>

Get Value from dropdown list and add it to a Gridview

I have two dropdown lists in asp.net which are generated from a database. When the user selected a value from the first dropdown list, the second dropdown list will be generated based on this value.
I also have a gridview with has a add row, delete and save function. Within each cell of the gridview are textboxes which are self generated by the add row function.
What I want to do is to have a add selected value button from the dropdown list and for the value of the second dropdown list to be added into the first cell of the gridview.
However, if there are muliple gridview rows generated, then a option should appear asking which row the value should be inserted into.
Please can I get some help on this?
Below is the ASP.net
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="workout">
<div class="exerciseDD">
<fieldset class="exercise">
<legend>Exercise List</legend>
<div style="text-align: justify">
To begin choose the exercise number you wish to add an exercise too. Then use
the dropdown menu to select the exercise you wish to use in your workout.
Finally click add to insert the exercise into the workout.
<br />
<br />
<asp:Label ID="Label3" runat="server" CssClass="bold"
Text="Choose an exercise number:"></asp:Label>
<br />
<asp:DropDownList ID="ExerNo" runat="server">
<asp:ListItem Selected="True">1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:Label ID="MuscleGDD" runat="server" CssClass="bold" Text="Muscle Group:"></asp:Label>
<br />
<asp:DropDownList ID="MuscleDD" runat="server" AutoPostBack="True"
Height="22px" onselectedindexchanged="MuscleDD_SelectedIndexChanged"
Width="100%">
</asp:DropDownList>
<br />
<br />
<asp:Label ID="Label4" runat="server" CssClass="bold" Text="Exercise Name:"></asp:Label>
<br />
<asp:DropDownList ID="ExerciseDD" runat="server" AutoPostBack="True"
Height="22px" onselectedindexchanged="ExerciseDD_SelectedIndexChanged"
Width="100%">
</asp:DropDownList>
<br />
<br />
<asp:Button ID="Add" runat="server" Text="Add Exercise" onclick="Add_Click" />
<br />
<asp:Label ID="Label5" runat="server" CssClass="bold"
Text="Exercise Description:"></asp:Label>
<br />
<asp:Label ID="Exerdes" runat="server"></asp:Label>
</div>
</fieldset>
</div>
<div class="createWO">
<fieldset class="create">
<legend>Create Workout</legend>
<asp:Label ID="LabelUserId" runat="server" Visible="True"></asp:Label>
<br />
<strong>Workout Name:</strong> <asp:TextBox ID="WorkName" runat="server"></asp:TextBox>
<div>
<asp:Label ID="CurrentDate" runat="server" />
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDeleting="grvWorkout_RowDeleting">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:BoundField DataField="Userid" HeaderText="User ID" Visible="false"/>
<asp:TemplateField HeaderText="Exercise Name">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Set">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Repetition">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"
onclick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:gridview>
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
<br />
<br />
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Below is the Code behind. The code contains the add row, delete and save function. The code also contains the functionality to populate the dropdown lists:
private void SetInitialRow()
{
//Sets the initial row of the gridview
}
private void AddNewRowToGrid()
{
//Adds a new row and placing any data back into the gridview
}
private void SetPreviousData()
{
//temp save of the dat
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable MuscleG = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Muscle_id], [MuscleName] FROM [MuscleGroup]", con);
adapter.Fill(MuscleG);
MuscleDD.DataSource = MuscleG;
MuscleDD.DataTextField = "MuscleName";
MuscleDD.DataValueField = "Muscle_id";
MuscleDD.DataBind();
}
//MuscleDD.Items.Insert(0, new ListItem("Select Muscle Name", "0"));
}
if (!Page.IsPostBack)
{
SetInitialRow();
}
CurrentDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
}
protected void MuscleDD_SelectedIndexChanged(object sender, EventArgs e)
{
int muscleid = Convert.ToInt32(MuscleDD.SelectedValue);
DataTable exercises = new DataTable();
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Exercise_id], [ExerciseName] FROM [Exercise] WHERE [Muscle_id] = " + muscleid, con2);
adapter.Fill(exercises);
ExerciseDD.DataSource = exercises;
ExerciseDD.DataTextField = "ExerciseName";
ExerciseDD.DataValueField = "Exercise_id";
ExerciseDD.DataBind();
}
//ExerciseDD.Items.Insert(0, new ListItem("Select Exercise", "0"));
}
protected void ExerciseDD_SelectedIndexChanged(object sender, EventArgs e)
{
int exerciseid = Convert.ToInt32(ExerciseDD.SelectedValue);
using (SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
con3.Open();
string cmdStr = "SELECT [Exercise_id], [ExerDesc] FROM [ExerciseDescription] WHERE [Exercise_id] = '" + exerciseid +"'";
SqlCommand Des = new SqlCommand(cmdStr, con3);
SqlDataReader reader = Des.ExecuteReader();
reader.Read();
Exerdes.Text = reader["ExerDesc"].ToString();
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void Button1_Click(object sender, EventArgs e)
{
//Saves data in gridview to database
}
//A method that returns a string which calls the connection string from the web.config
private string GetConnectionString()
{
}
//A method that Inserts the records to the database
private void InsertRecords(StringCollection sc)
{
//Inserts the records into the database
}
protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
private void SetRowData()
{
//Set data in temp table
}
protected void grvWorkout_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//Deletes the row
}
//This function relates to the button I wish to insert the value of the dropdown menu into the gridview.
protected void Add_Click(object sender, EventArgs e)
{
//Add dropdown value
}
Here is a quick & dirty sample I made based on your requirement to get you started.
You can select a car make & get selected models
You can add rows to the gridview on button click
You can select the stock model's properties on checkbox click of gridview
Aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="gridTest.aspx.cs" Inherits="WebApplication1.Gridview" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Make:
<asp:DropDownList ID="ddlMake" runat="server" AppendDataBoundItems="True" AutoPostBack="True"
OnSelectedIndexChanged="ddlMake_SelectedIndexChanged">
<asp:ListItem Text=" - Select -" Value=""></asp:ListItem>
</asp:DropDownList>
<br />
Model:
<asp:DropDownList ID="ddlModels" runat="server">
</asp:DropDownList>
<br />
<br />
<h2>
Accessories
<asp:Button ID="btnAddConsignment" runat="server" OnClick="btnAddConsignment_Click"
Text="Add Consignment" />
</h2>
<asp:GridView ID="gvItems" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Consignment No.">
<ItemTemplate>
<%# Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Color">
<itemtemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</itemtemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tires">
<itemtemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</itemtemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NOS">
<itemtemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</itemtemplate>
</asp:TemplateField>
<asp:TemplateField>
<itemtemplate><asp:CheckBox ID="cbSameAsStock" runat="server" AutoPostBack="True"
oncheckedchanged="cbSameAsStock_CheckedChanged" Text="Same as stock?" /></itemtemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebApplication1
{
public partial class Gridview : System.Web.UI.Page
{
public class Make
{
public int Id { get; set; }
public string Name { get; set; }
public List<Make> GetMake()
{
return new List<Make>()
{
new Make { Id = 1, Name = "Ford" },
new Make { Id = 2, Name = "BMW" },
new Make { Id = 3, Name = "Lamborghini" }
}.ToList();
}
}
public class Models
{
public int ModelId { get; set; }
public int MakeId { get; set; }
public string Name { get; set; }
public List<Models> GetModels()
{
return new List<Models>()
{
new Models { ModelId=1, MakeId=1, Name="Ford Truck 1"},
new Models { ModelId=2, MakeId=1, Name="Ford Truck 2"},
new Models { ModelId=3, MakeId=1, Name="Ford Truck 3"},
new Models { ModelId=4, MakeId=3, Name="Gollarado"},
new Models { ModelId=5, MakeId=3, Name="Murcillago"}
};
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Temporary data fetched through a list. In production you will fetch data from the database
Make make = new Make();
ddlMake.DataSource = make.GetMake();
ddlMake.DataTextField = "Name";
ddlMake.DataValueField = "Id";
ddlMake.DataBind();
if(ViewState["dt"]!=null)
{
DataTable dt = ViewState["dt"] as DataTable;
gvItems.DataSource = dt;
}
}
}
protected void ddlMake_SelectedIndexChanged(object sender, EventArgs e)
{
// Filter second dropdown list
Models model = new Models();
ddlModels.DataSource = model.GetModels().Where(s => s.MakeId == int.Parse(ddlMake.SelectedValue));
ddlModels.DataTextField = "Name";
ddlModels.DataValueField = "ModelId";
ddlModels.DataBind();
}
protected void btnAddConsignment_Click(object sender, EventArgs e)
{
// Bind gridview to temporary data & store inside viewstate
DataTable dt = null;
if (ViewState["dt"] == null)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(int)));
dt.Columns.Add(new DataColumn("Color", typeof(string)));
dt.Columns.Add(new DataColumn("Tires", typeof(string)));
dt.Columns.Add(new DataColumn("NOS", typeof(string)));
dt.Columns["Id"].AutoIncrement = true;
dt.Columns["Id"].AutoIncrementSeed = 1;
}
else
dt = ViewState["dt"] as DataTable;
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
gvItems.DataSource = dt;
gvItems.DataBind();
ViewState["dt"] = dt;
}
protected void cbSameAsStock_CheckedChanged(object sender, EventArgs e)
{
// Get your checkbox from gridview's selected row
CheckBox cbTemp = sender as CheckBox;
if (cbTemp != null)
{
// If selected, append selected model name to textboxes
if (cbTemp.Checked)
{
var selectedModel = ddlModels.SelectedItem.Text; // your selected car model
GridViewRow gr = ((CheckBox) sender).NamingContainer as GridViewRow;
if (gr != null)
{
TextBox txt1 = gr.FindControl("TextBox1") as TextBox;
TextBox txt2 = gr.FindControl("TextBox2") as TextBox;
TextBox txt3 = gr.FindControl("TextBox3") as TextBox;
txt1.Text = "Same as stock "+ selectedModel;
txt2.Text = "Same as stock " + selectedModel;
txt3.Text = "Same as stock " + selectedModel;
}
}
}
}
}
}

Asp.net object reference error

In asp.net web application I get this error when populating datalist from database.
In design page I have some labels inside an item-template tag, when I try to access these labels by FindControl it gives the error:
Object reference not set to an instance of object
here is my code:
Products.aspx.cs:
public partial class Products : System.Web.UI.Page
{
Product product;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
DataList1.DataBind();
product = this.getProducts();
Label TitleLabel = (Label)DataList1.FindControl("TitleLabel");
TitleLabel.Text = product.Name;
Label DescLabel = (Label)DataList1.FindControl("DescLabel");
DescLabel.Text = product.LongDescription;
Label PriceLabel = (Label)DataList1.FindControl("PriceLabel");
PriceLabel.Text = product.UnitPrice.ToString();
ImageButton PImage = (ImageButton)DataList1.FindControl("ImageButton1");
PImage.ImageUrl = "images/"+product.ImageFile;
}
private Product getProducts()
{
Product p = new Product();
DataView productsTable = (DataView)
SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView row in productsTable)
{
p.ProductID = row["P_Id"].ToString();
p.Name = row["Title"].ToString();
p.ShortDescription = row["Desc"].ToString();
p.LongDescription = row["Desc_full"].ToString();
p.UnitPrice = Convert.ToDecimal(row["Price"]);
p.ImageFile = row["imageurl"].ToString();
}
return p;
}
}
Products.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Products.aspx.cs" Inherits="ECProject.Products" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server" DataKeyField="P_Id"
DataSourceID="SqlDataSource1" RepeatColumns="4"
RepeatDirection="Horizontal" CellPadding="4" ForeColor="#333333" >
<AlternatingItemStyle BackColor="White" ForeColor="#284775" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<ItemStyle BackColor="#F7F6F3" ForeColor="#333333" />
<ItemTemplate >
<asp:ImageButton ID="ImageButton1" runat="server" Height = "200px"/>
<br />
Title:
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
<br />
Brand:
<asp:Label ID="DescLabel" runat="server" Text='<%# Eval("Desc") %>' />
<br />
Available:
<asp:Label ID="Is_ActiveLabel" runat="server" Text='<%# Eval("Is_Active") %>' />
<br />
Price:
<asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("Price") %>' />
<br />
</ItemTemplate>
<SelectedItemStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ECDB.mdf;Integrated Security=True;User Instance=True"
ProviderName="System.Data.SqlClient" SelectCommand="SELECT * FROM [Product]">
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
Error:
Line 25:
Line 26: Label TitleLabel = (Label)DataList1.FindControl("TitleLabel");
Line 27: TitleLabel.Text = product.Name;
Line 28:
Line 29:
Please help, how to get rid of this error ?
The list usually contains more than one item, so your logic is flawed. What you can do it handle the ItemDataBound event of the list by adding such line in your Page_Load:
DataList1.ItemDataBound += new DataListItemEventHandler(DataList1_ItemDataBound);
And have such method:
void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label TitleLabel = (Label)e.Item.FindControl("TitleLabel");
TitleLabel.Text = "changed by code";
}
}
To customize your individual DataList items, you need to do it in the ItemDataBound event. Check out this tutorial for more details.
However, it looks like you are approaching your task in an incorrect manner. Bottom line is that you need to bind your DataSource to a collection of items, and you are trying to feed it items one-by-one. Let me know if I misunderstood you and you do need to bind an individual Product to your DataList customizing its appearance at bind time.
I think your lable put in other object same as panel. you should find the real name of your lable in html code, so the best way is putting a mistake error in you script code as a result when your solution is runnig it will stop and you can find the real name of your lable control. Then use below code :
Label TitleLabel = (Label)DataList1.FindControl("REAL NAME OF LABEL CONTROL");
I hope it can help you.

how to grab the Ctl from a linkbutton

I have a gridview which is pulling it data from a stored procedure. In the column title, I have used a Linkbutton. I would like to grab the Ctl ID and store it in a variable when it is clicked. I am not sure what is happening, but I get a few strings going through. Below is my code and this is similar to my previous post.
ASP.NET
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:LinkButton ID="lnkID" runat="server" OnClick="lblClick1"
Text='<%#Eval("ID") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
C#:
GridViewRow row = gv2.SelectedRow;
string controlId = ((LinkButton)row.FindControl("lnkID")).ID;
lblshow.Text = controlId;
Can someone help me get up and running. Thanks.
You could use a hidden field to store the id:
<ItemTemplate>
<asp:HiddenField
runat="server"
ID="ID"
Value='<%# Eval("ID") %>'
/>
<asp:LinkButton
runat="server"
OnClick="LabelClick"
Text="click me"
/>
</ItemTemplate>
and then:
protected void LabelClick(object sender, EventArgs e)
{
var hiddenField = (HiddenField)((Control)sender).FindControl("ID");
var id = hiddenField.Value;
// Do something with the id
}
UPDATE:
Full working example:
<%# Page Language="C#" %>
<script type="text/c#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grid.DataSource = Enumerable.Range(1, 10).Select(x => new
{
ID = x
});
grid.DataBind();
}
}
protected void LabelClick(object sender, EventArgs e)
{
var hiddenField = (HiddenField)((Control)sender).FindControl("ID");
result.Text = string.Format("selected id: {0}", hiddenField.Value);
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:HiddenField
runat="server"
ID="ID"
Value='<%#Eval("ID") %>'
/>
<asp:LinkButton
runat="server"
OnClick="LabelClick"
Text="click me"
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="result" runat="server" />
</form>
</body>
</html>
In the OnClick method lblClick1 you can use:
public void lblClick1(object sender, CommandEventArgs e)
{
int controlId = Convert.ToInt32(e.CommandArgument); //get ID and store it in controlId
lblshow.Text = controlId;
}

Categories