Search SQL Server Table Using Simple ASP.NET Search Bar - c#

Thank you for taking the time to read my request. I am new to ASP.Net and I am trying to figure out how to implement a textbox/button that will search a SQL Server database and grab results based on queries that are 'like' an attribute. Here is what I have so far...
ASPX Main file:
<%# Page Title="" Language="C#" MasterPageFile="~/PantryAdmin.Master" AutoEventWireup="true" CodeFile="Products.aspx.cs" Inherits="RampantryF.Products" %>
<asp:Content runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<!DOCTYPE html>
<script runat="server">
public string SearchString
{
get { return TextBox4.Text; }
}
</script>
<html>
<head>
<title></title>
</head>
<body>
<div>
/*Search box*/
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<asp:Button ID="Button1" PostBack="" runat="server" Text="Search" />
<asp:Label ID="SearchBox" runat="server" Text="Label" ForeColor="Maroon"></asp:Label>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1" AllowPaging="True" PageSize="5" AllowSorting="True">
<Columns>
<asp:BoundField DataField="PRODUCT_ID" HeaderText="PRODUCT_ID" ReadOnly="True" SortExpression="PRODUCT_ID" />
<asp:BoundField DataField="UPC_CODE" HeaderText="UPC_CODE" ReadOnly="True" SortExpression="UPC_CODE" />
<asp:BoundField DataField="PRODUCT_NAME" HeaderText="PRODUCT_NAME" ReadOnly="True" SortExpression="PRODUCT_NAME" />
<asp:BoundField DataField="PRODUCT_TYPE" HeaderText="PRODUCT_TYPE" ReadOnly="True" SortExpression="PRODUCT_TYPE" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RampantryDB %>" SelectCommand="SELECT * FROM [PRODUCT]"></asp:SqlDataSource>
<fieldset>
<asp:DetailsView
ID="dtlDonor"
DataSourceID="ObjectDataSource1"
DefaultMode="Insert" Caption="Add Product (C)"
AutoGenerateRows="False"
runat="server">
<Fields>
<asp:BoundField DataField="PRODUCT_ID" HeaderText="PRODUCT_ID" ReadOnly="True" SortExpression="PRODUCT_ID" Visible="False" />
<asp:TemplateField HeaderText="UPC_CODE" SortExpression="UPC_CODE">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("UPC_CODE") %>'></asp:Label>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("UPC_CODE") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("UPC_CODE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PRODUCT_NAME" SortExpression="PRODUCT_NAME">
<EditItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("PRODUCT_NAME") %>'></asp:Label>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("PRODUCT_NAME") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("PRODUCT_NAME") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PRODUCT_TYPE" SortExpression="PROUDUCT_TYPE">
<EditItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("PRODUCT_TYPE") %>'></asp:Label>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("PRODUCT_TYPE") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("PRODUCT_TYPE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
</fieldset>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SortParameterName="OrderBy" MaximumRowsParameterName="PageSize" DeleteMethod="Delete" InsertMethod="Insert" SelectMethod="SelectAll" TypeName="RampantryF.App_Code.BLL.PRODUCT" UpdateMethod="Update">
<DeleteParameters>
<asp:Parameter Name="PRODUCT_ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="UPC_CODE" Type="Double" />
<asp:Parameter Name="PRODUCT_NAME" Type="String" />
<asp:Parameter Name="PRODUCT_TYPE" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="PRODUCT_ID" Type="Int32" />
<asp:Parameter Name="UPC_CODE" Type="Double" />
<asp:Parameter Name="PRODUCT_NAME" Type="String" />
<asp:Parameter Name="PRODUCT_TYPE" Type="String" />
</UpdateParameters>
</asp:ObjectDataSource>
Behind 'Products.aspx.cs' code file:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace RampantryF
{
public partial class Products : System.Web.UI.Page
{
public SqlConnection con;
public string constr;
public void connection()
{
constr = ConfigurationManager.ConnectionStrings["PRODUCT"].ToString();
con = new SqlConnection(constr);
con.Open();
}
protected void Page_Load(object sender, EventArgs e)
{
SearchBox.Visible = false;
}
private void rep_bind()
{
connection();
string query = "select * from PRODUCT where PRODUCT_NAME like'" + TextBox4.Text + "%'";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
connection();
string query = "select PRODUCT_NAME from PRODUCT where PRODUCT_NAME like'" + TextBox4.Text + "%'";
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr;
dr = com.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
rep_bind();
GridView1.Visible = true;
TextBox4.Text = "";
SearchBox.Text = "";
}
else
{
GridView1.Visible = false;
SearchBox.Visible = true;
SearchBox.Text = "The search Term " + TextBox4.Text + " Is Not Available in the Records"; ;
}
}
}
}
BLL Products.cs File:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RampantryF.App_Code.DAL;
namespace RampantryF.App_Code.BLL
{
public class PRODUCT
{
private int _PRODUCT_ID;
private double _UPC_CODE = 0;
private string _PRODUCT_NAME = String.Empty;
private string _PRODUCT_TYPE = String.Empty;
///Product Unique Identifier
public int PRODUCT_ID
{
get { return _PRODUCT_ID; }
}
///Product UPC_CODE
///
public double UPC_CODE
{
get { return _UPC_CODE; }
}
///Product PRODUCT_NAME
///
public string PRODUCT_NAME
{
get { return _PRODUCT_NAME; }
}
/// <summary>
/// Product PRODUCT_TYPE
/// </summary>
public string PRODUCT_TYPE
{
get { return _PRODUCT_TYPE; }
}
///retrieves all products
///
public static List<PRODUCT> SelectAll()
{
DBUtils DBUtils = new DBUtils();
return DBUtils.PRODUCTSelectAll();
}
public static List<PRODUCT> SelectAll(string OrderBy)
{
DBUtils DBUtils = new DBUtils();
return DBUtils.PRODUCTSelectAll(OrderBy);
}
///Updates a particular product
///
public static void Update(int PRODUCT_ID, double UPC_CODE, string PRODUCT_NAME, string PRODUCT_TYPE)
{
if (PRODUCT_ID < 1)
throw new ArgumentException("Product Id must be greater than 0", "id");
PRODUCT ProductToUpdate = new PRODUCT(PRODUCT_ID, UPC_CODE, PRODUCT_NAME, PRODUCT_TYPE);
ProductToUpdate.Save();
}
///inserts new product
///
public static void Insert(double UPC_CODE, string PRODUCT_NAME, string PRODUCT_TYPE)
{
PRODUCT newProduct = new PRODUCT(UPC_CODE, PRODUCT_NAME, PRODUCT_TYPE);
newProduct.Save();
}
///Deletes an Existing Product
///
public static void Delete(int PRODUCT_ID)
{
if (PRODUCT_ID < 1)
throw new ArgumentException("Product Id must be greater than 0", "id");
DBUtils DBUtils = new DBUtils();
DBUtils.PRODUCTDelete(PRODUCT_ID);
}
///validates Product information before saving Product
///properties to database
///
private void Save()
{
if (String.IsNullOrEmpty(_PRODUCT_NAME))
throw new ArgumentException("Product PRODUCT_NAME not supplied", "PRODUCT_NAME");
DBUtils DBUtils = new DBUtils();
if (_PRODUCT_ID > 0)
DBUtils.PRODUCTUpdate(this);
else
DBUtils.PRODUCTInsert(this);
}
///Intializes Product
///
public PRODUCT(int PRODUCT_ID, double UPC_CODE, string PRODUCT_NAME, string PRODUCT_TYPE)
{
_PRODUCT_ID = PRODUCT_ID;
_UPC_CODE = UPC_CODE;
_PRODUCT_NAME = PRODUCT_NAME;
_PRODUCT_TYPE = PRODUCT_TYPE;
}
public PRODUCT(double UPC_CODE, string PRODUCT_NAME, string PRODUCT_TYPE)
{
_UPC_CODE = UPC_CODE;
_PRODUCT_NAME = PRODUCT_NAME;
_PRODUCT_TYPE = PRODUCT_TYPE;
}
}
}
Any help anyone can provide is very much appreciated! Again, I am new to this, and I have been following tutorials and googling the internet trying to find a solution but cannot find one.
As of now, the page loads, but it will not actually search when the button is clicked. I would like it to change the GridView1 with all of the records into records that fill into a 'LIKE Textbox4' query.
Thank you!

You need to add click event to your search button like OnClick="Button1_Click"
<asp:Button ID="Button1" PostBack="" runat="server" Text="Search" OnClick="Button1_Click" />
also note that, inside button click event again you are calling another method to bind data to same gridview. You will lost what ever you have bind in the click event from this second method.

Related

GridView Disappears on Update Button Click, Doesn't Update Record

So I have a c# page with a GridView. For some reason, after adding the label and the template for editing, when I click the update button in the edit column, the GridView disappears and none of the records get changed. I know I need to databind the values in the edit box once the user clicks update but I'm not sure how. Can anyone give any suggestions?
Here is my code.
public partial class CMSWebParts_Custom_Development_DevWebPart :
CMSAbstractWebPart
{
public string paramId;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["RefUrl"] = Request.UrlReferrer.ToString();
}
string urlString = Request.UrlReferrer.ToString();
paramId = HttpUtility.ParseQueryString(urlString).Get("Theid");
DispatchNumberLabel.Text = getDispatchNumber();
//TerminalLabel.Text = getTerminal();
DispatchInfoIdLabel.Text = getDispatchInfoId();
DriverNameLabel.Text = getDriverName();
}
protected string getDispatchInfoId()
{
string result = DriverDropDownList.SelectedValue;
return result;
}
protected string getDispatchNumber()
{
string result = paramId;
return result;
}
protected string getTerminal()
{
string result;
string connectionString = "";
using (var con = new SqlConnection(connectionString))
{
var sql = "Select Terminal from Form_IntranetSharpTransit_DispatchInfo where ([Dispatch] = #Dispatch)";
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#Dispatch", getDispatchNumber());
con.Open();
result = (string)cmd.ExecuteScalar();
}
}
return result;
}
protected string getDriverName()
{
string result;
string connectionString = "";
using (var con = new SqlConnection(connectionString))
{
var sql = "Select Driver from Form_IntranetSharpTransit_DispatchInfo WHERE ([DispatchInfoID] = #DispatchInfoId)";
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#DispatchInfoId", getDispatchInfoId());
con.Open();
result = (string)cmd.ExecuteScalar();
}
}
return result;
}
}
And here is my code behind.
<%# Control Language="C#" AutoEventWireup="true"
CodeFile="~/CMSWebParts/Custom/Development/DevWebPart.ascx.cs"
Inherits="CMSWebParts_Custom_Development_DevWebPart" %>
<%--<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
}
</script>--%>Dispatch Number:
<asp:Label ID="DispatchNumberLabel" runat="server"></asp:Label>
<p>
Terminal:
<asp:Label ID="TerminalLabel" runat="server"></asp:Label>
</p>
<p>
Current
Dispatch Info ID:
<asp:Label ID="DispatchInfoIdLabel" runat="server"></asp:Label>
</p>
<p>
Driver Name:
<asp:Label ID="DriverNameLabel" runat="server"></asp:Label>
</p>
<asp:DropDownList ID="DriverDropDownList" runat="server" AutoPostBack="True"
DataSourceID="DriverListData" DataTextField="Select Driver"
DataValueField="Column1">
</asp:DropDownList>
<asp:SqlDataSource ID="DriverListData" runat="server" ConnectionString="<%$
ConnectionStrings:ConnectionString %>" ProviderName="<%$
ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="Select
'', 'Select Driver' as 'Select Driver'
from Form_IntranetSharpTransit_DispatchInfo
Union
SELECT DispatchInfoID, Driver + ' - ' + CAST(DispatchInfoID AS
varchar(50)) AS Expr1
FROM Form_IntranetSharpTransit_DispatchInfo
WHERE (Dispatch = ?) AND (DaysOff NOT LIKE '%' + (SELECT DispatchDay
FROM Form_IntranetSharpTransit_DailyDispatch Where DailydispatchID = ?) +
'%') AND (Status LIKE 'Available')">
<SelectParameters>
<asp:QueryStringParameter Name="?" QueryStringField="Theid" />
<asp:QueryStringParameter Name="?" QueryStringField="Theid" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AutoGenerateEditButton="True" DataSourceID="Store1Data" EditIndex="0"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Store 1:">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"
OnTextChanged="TextBox1_TextChanged" Text='<%# Bind("[Store Number]") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("[Store
Number]") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="Store1Data" runat="server" ConnectionString="<%$
ConnectionStrings:ConnectionString %>" ProviderName="<%$
ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT
(SELECT Store
FROM Form_IntranetSharpTransit_TourPlan
WHERE (TourPlanID =
Form_IntranetSharpTransit_DispatchInfo_1.Store1)) AS 'Store Number',
Location1, Pro1, Store1Export
FROM Form_IntranetSharpTransit_DispatchInfo AS
Form_IntranetSharpTransit_DispatchInfo_1
WHERE (DispatchInfoID = ?)">
<SelectParameters>
<asp:ControlParameter ControlID="DriverDropDownList" Name="?"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
All I want is to display the table with an edit button. When the edit button is clicked, I want the label in table to become an edit box (as my template shows). After the user has modified the edit box, they can then click the update button, committing the change to the database and refreshing the table to show the changed values.
This seems extremely simple but I have been struggling with it for about 3 months now.
Please help.
Here's a minimal, yet working, example of what you are trying to achieve.
Though I must admit, the Microsoft Documentation came in pretty handy for this snippet.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UpdateGridViewOnPostBack_45921943.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="dgv1" AutoGenerateEditButton="true" OnRowEditing="dgv1_RowEditing" OnRowUpdating="dgv1_RowUpdating">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="gvCol1Label" Text='<%#Bind("field1") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="gvCol1Txtbx" Text='<%# Bind("field1") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web.UI.WebControls;
using System.Collections.ObjectModel;
namespace UpdateGridViewOnPostBack_45921943
{
public partial class Default : System.Web.UI.Page
{
static ObservableCollection<dgvEntry> dgv1Source;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Not a postback
dgv1Source = new ObservableCollection<dgvEntry>();
dgv1Source.Add(new dgvEntry { field1 = "the field coming from the data source" });
initializeDGV(IsPostBack);
}
else
{
//is a postback
if (dgv1Source == null)
{
dgv1Source = new ObservableCollection<dgvEntry>();
}
initializeDGV(IsPostBack);
}
}
private void initializeDGV(bool isPostback)
{
dgv1.DataSource = dgv1Source;
dgv1.AutoGenerateColumns = false;
if (!isPostback)
{
dgv1.DataBind();
}
}
protected void dgv1_RowEditing(object sender, GridViewEditEventArgs e)
{
dgv1.EditIndex = e.NewEditIndex;
dgv1.DataBind();
}
protected void dgv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = dgv1.Rows[e.RowIndex];
dgv1Source[e.RowIndex].field1 = ((TextBox)row.Cells[1].Controls[1]).Text;
dgv1.EditIndex = -1;
dgv1.DataBind();
}
}
public class dgvEntry
{
public string field1 { get; set; }
//public string field2 { get; set; }
//public string field3 { get; set; }
}
}

How to update the page without reload using update panel ?AP.NET C#

I have a gridview which contains an edit and a delete command.
I would like that when I click on edit, update the value, and click on delete that the value is deleted from database and the page is not reloaded.
Now, I use update panel and script manager but the page is reloaded again, the Update panel is not working. And my other problem is when I put <form runat="server"></form> form tag before gridview then it's working fine, the gridview shows, but when I remove this tag then an error appears:
object reference not set instance object.
My aspx code is :
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate>
<form runat="server"></form>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Database_id" Height="184px"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" style="margin-left: 181px" Width="361px"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Database Name">
<EditItemTemplate>
<asp:TextBox ID="txtDatabaseName" runat="server" Height="22px"
Text='<%# Eval("Database_Name") %>' Width="192px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Database_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<EditItemTemplate>
<asp:TextBox ID="txtdescription" runat="server" Height="24px"
Text='<%# Eval("Description") %>' Width="209px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Operations" ShowDeleteButton="True"
ShowEditButton="True" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
</ContentTemplate></asp:UpdatePanel>
</asp:Content>
and my aspx.cs code is :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
private void binddata()
{
string con = "Data Source=HAMEED_KHAN\\SQLEXPRESS;Initial Catalog=db_compiler;Integrated Security=True";
DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection(con))
{
string user = Session["name"].ToString();
SqlCommand cmd2 = new SqlCommand("SELECT User_ID from tbl_user WHERE User_Name='" + user + "'", cnn);
cnn.Open();
string id = cmd2.ExecuteScalar().ToString();
int ID = Int32.Parse(id);
SqlDataAdapter da = new SqlDataAdapter("SELECT Database_id,Database_Name,Description,Date FROM Create_db WHERE User_ID='" + ID + "'", cnn);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
binddata();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
delete(id);
GridView1.EditIndex = -1;
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox txtDatabaseName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDatabaseName");
TextBox txtdescription = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtdescription");
updatedb(txtDatabaseName.Text, txtdescription.Text, id);
GridView1.EditIndex = -1;
binddata();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
binddata();
}
private void updatedb(string dbname, string Dis, int id)
{
string con = "Data Source=HAMEED_KHAN\\SQLEXPRESS;Initial Catalog=db_compiler;Integrated Security=True";
using (SqlConnection cnn = new SqlConnection(con))
{
string query = "UPDATE Create_db SET Database_Name='" + dbname + "',Description='" + Dis + "' WHERE Database_id='" + id + "' ";
SqlCommand cmd = new SqlCommand(query, cnn);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
private void delete(int id)
{
string con = "Data Source=HAMEED_KHAN\\SQLEXPRESS;Initial Catalog=db_compiler;Integrated Security=True";
using (SqlConnection cnn = new SqlConnection(con))
{
string query = "DELETE FROM Create_db WHERE Database_id='" + id + "' ";
SqlCommand cmd = new SqlCommand(query, cnn);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
Your code is not well formatted, the UpdatePanel is outside the form, and gridview also is outside the form. It must be like that...
<form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView>
...
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
First things first:
<%-- Your code (fragment) --%>
<EditItemTemplate>
<asp:TextBox ID="txtDatabaseName" runat="server" Height="22px"
Text='<%# Eval("Database_Name") %>' Width="192px"></asp:TextBox>
</EditItemTemplate>
Eval is ReadOnly (OneWay) binding. It should be
<asp:TextBox ID="txtDatabaseName" runat="server" Height="22px"
Text='<%# Bind("Database_Name") %>' Width="192px"></asp:TextBox>
Next. I would recommend you to use <asp:SqlDataSource... which takes all dirty work to itself (select, update, and delete). You can sent your UserID parameter to the parameters like this:
<asp:Literal ID="userId" runat="server" Visible="false"></asp:Literal>
...
<asp:SqlDataSource ID="sqlDS"...
<SelectParameters>
<asp:ControlParameter ControlID="userId" PropertyName="Text" Name="ID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
...
In GridView add DataSourseID="sqlDS"
In Page_load set value userId.Text=ID.ToString();
Try this way.

how to populate a dropdownlist based on selection of another dropdownlist in a gridview

I have a gridview with it's own sqlDataSource. In the footer row, I have an Insert field to create a new row. However, that footer row is quite complex and I'm trying to figure out how to make it work.
What I would like to see happen, is that a user Selects the OTypeName ddl. Based on that selection, the OSpecies ddl is enabled and populates values based on the OTypeName ddl. The same can be said in relation to OSpecies and OVariety.
The user then inputs their own information into OAge, OYields, OPlantDate, and OPlantFrom.
The rest of the fields in the footer row are labels that will be populated based on the final OVariety selection.
The Insert button then adds all these columns to the gridview.
I only need help with populating one ddl based on the ddl selection of another and how to populate a label based on a ddl selection.
Here's my code in the aspx file:
<%# Page Title="" Language="C#" MasterPageFile="~/Permaculture.Master" AutoEventWireup="true" CodeBehind="OrchardMainWebForm.aspx.cs" Inherits="PermacultureOrganizer.OrchardMainWebForm" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Content" runat="server" >
<asp:GridView ID="gvOrchardData" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="OUserOrchardID" DataSourceID="dsOrchardDatabase" CellPadding="4" CellSpacing="4" ForeColor="#333333" GridLines="Vertical" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" ShowFooter="True" Font-Bold="False">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="OUserOrchardID" InsertVisible="False" SortExpression="OUserOrchardID">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("OUserOrchardID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("OUserOrchardID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lbInsert"
runat="server"
OnClick="lbInsert_Click" ForeColor="White">Insert</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OTypeName" SortExpression="OTypeName">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1"
runat="server"
AutoPostBack="True"
DataSourceID="dsTypeName"
DataTextField="OrchardTypeName"
DataValueField="OrchardTypeID" >
</asp:DropDownList>
<asp:SqlDataSource ID="dsTypeName" runat="server" ConnectionString="<%$ ConnectionStrings:DB_9DE518_PermacultureConnectionString %>" SelectCommand="SELECT * FROM [tblOrchardType]"></asp:SqlDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("OTypeName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlTypeName"
runat="server"
AutoPostBack="True"
DataSourceID="dsTypeName"
DataTextField="OrchardTypeName"
DataValueField="OrchardTypeID"
>
</asp:DropDownList>
<asp:SqlDataSource ID="dsTypeName" runat="server" ConnectionString="<%$ ConnectionStrings:DB_9DE518_PermacultureConnectionString %>" SelectCommand="SELECT * FROM [tblOrchardType]"></asp:SqlDataSource>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OSpecies" SortExpression="OSpecies">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2"
runat="server"
SelectedValue='<%# Bind("OSpecies") %>'
AutoPostBack="True"
DataSourceID="dsSpecies"
DataTextField="Species"
DataValueField="OrchardTypeID">
<asp:ListItem>Select Species</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="dsSpecies" runat="server" ConnectionString="<%$ ConnectionStrings:DB_9DE518_PermacultureConnectionString %>" SelectCommand="SELECT [Species], [OrchardTypeID] FROM [tblOrchardItem]"></asp:SqlDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("OSpecies") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlSpecies"
runat="server"
AutoPostBack="True"
DataSourceID="dsSpecies"
DataTextField="Species"
DataValueField="OrchardTypeID"
>
<asp:ListItem>Select Species</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="dsSpecies" runat="server" ConnectionString="<%$ ConnectionStrings:DB_9DE518_PermacultureConnectionString %>" SelectCommand="SELECT [Species], [OrchardTypeID] FROM [tblOrchardItem]">
</asp:SqlDataSource>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OVariety" SortExpression="OVariety">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList3"
runat="server"
AutoPostBack="True"
DataSourceID="dsVariety"
DataTextField="Variety"
DataValueField="OrchardTypeID">
</asp:DropDownList>
<asp:SqlDataSource ID="dsVariety" runat="server" ConnectionString="<%$ ConnectionStrings:DB_9DE518_PermacultureConnectionString %>" SelectCommand="SELECT [Variety], [OrchardTypeID] FROM [tblOrchardItem]"></asp:SqlDataSource>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlVariety"
runat="server"
AutoPostBack="True"
DataSourceID="dsVariety"
DataTextField="Variety"
DataValueField="OrchardTypeID"
>
</asp:DropDownList>
<asp:SqlDataSource ID="dsVariety" runat="server" ConnectionString="<%$ ConnectionStrings:DB_9DE518_PermacultureConnectionString %>" SelectCommand="SELECT [Variety], [OrchardTypeID] FROM [tblOrchardItem]"></asp:SqlDataSource>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("OVariety") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OAge" SortExpression="OAge">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("OAge") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBxAge" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("OAge") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OYields" SortExpression="OYields">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("OYields") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBxYields" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Bind("OYields") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OPlantDate" SortExpression="OPlantDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("OPlantDate") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBxPlantDate" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# Bind("OPlantDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OPlantFrom" SortExpression="OPlantFrom">
<EditItemTemplate>
<asp:TextBox ID="TextBox7" runat="server" Text='<%# Bind("OPlantFrom") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBxPlantFrom" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label8" runat="server" Text='<%# Bind("OPlantFrom") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OTreeSpacing" SortExpression="OTreeSpacing">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("OTreeSpacing") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTreeSpacing" runat="server"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Bind("OTreeSpacing") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OFertilizingTimes" SortExpression="OFertilizingTimes">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("OFertilizingTimes") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lblFertilizingTimes" runat="server"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label10" runat="server" Text='<%# Bind("OFertilizingTimes") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OWateringNeeds" SortExpression="OWateringNeeds">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("OWateringNeeds") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lblWateringNeeds" runat="server"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("OWateringNeeds") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OPollination" SortExpression="OPollination">
<EditItemTemplate>
<asp:TextBox ID="TextBox8" runat="server" Text='<%# Bind("OPollination") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lblPollination" runat="server"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label12" runat="server" Text='<%# Bind("OPollination") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OFertilizer" SortExpression="OFertilizer">
<EditItemTemplate>
<asp:TextBox ID="TextBox9" runat="server" Text='<%# Bind("OFertilizer") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lblFertilizer" runat="server"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label13" runat="server" Text='<%# Bind("OFertilizer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OPesticide" SortExpression="OPesticide">
<EditItemTemplate>
<asp:TextBox ID="TextBox10" runat="server" Text='<%# Bind("OPesticide") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lblPesticide" runat="server"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label14" runat="server" Text='<%# Bind("OPesticide") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="Black" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
<asp:SqlDataSource ID="dsOrchardDatabase" runat="server"
ConnectionString="<%$ ConnectionStrings:DB_9DE518_PermacultureConnectionString %>"
SelectCommand="SELECT * FROM [tblUserOrchard]" DeleteCommand="DELETE FROM [tblUserOrchard] WHERE [OUserOrchardID] = #OUserOrchardID" InsertCommand="INSERT INTO [tblUserOrchard] ([OTypeName], [OSpecies], [OVariety], [OAge], [OYields], [OPlantDate], [OPlantFrom], [OTreeSpacing], [OFertilizingTimes], [OPruningTimes], [OWateringNeeds], [OPollination], [OFertilizer], [OPesticide]) VALUES (#OTypeName, #OSpecies, #OVariety, #OAge, #OYields, #OPlantDate, #OPlantFrom, #OTreeSpacing, #OFertilizingTimes, #OPruningTimes, #OWateringNeeds, #OPollination, #OFertilizer, #OPesticide)" UpdateCommand="UPDATE [tblUserOrchard] SET [OTypeName] = #OTypeName, [OSpecies] = #OSpecies, [OVariety] = #OVariety, [OAge] = #OAge, [OYields] = #OYields, [OPlantDate] = #OPlantDate, [OPlantFrom] = #OPlantFrom, [OTreeSpacing] = #OTreeSpacing, [OFertilizingTimes] = #OFertilizingTimes, [OPruningTimes] = #OPruningTimes, [OWateringNeeds] = #OWateringNeeds, [OPollination] = #OPollination, [OFertilizer] = #OFertilizer, [OPesticide] = #OPesticide WHERE [OUserOrchardID] = #OUserOrchardID">
<DeleteParameters>
<asp:Parameter Name="OUserOrchardID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="OTypeName" Type="String" />
<asp:Parameter Name="OSpecies" Type="String" />
<asp:Parameter Name="OVariety" Type="String" />
<asp:Parameter Name="OAge" Type="Int32" />
<asp:Parameter Name="OYields" Type="String" />
<asp:Parameter Name="OPlantDate" Type="String" />
<asp:Parameter Name="OPlantFrom" Type="String" />
<asp:Parameter Name="OTreeSpacing" Type="String" />
<asp:Parameter Name="OFertilizingTimes" Type="String" />
<asp:Parameter Name="OPruningTimes" Type="String" />
<asp:Parameter Name="OWateringNeeds" Type="String" />
<asp:Parameter Name="OPollination" Type="String" />
<asp:Parameter Name="OFertilizer" Type="String" />
<asp:Parameter Name="OPesticide" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="OTypeName" Type="String" />
<asp:Parameter Name="OSpecies" Type="String" />
<asp:Parameter Name="OVariety" Type="String" />
<asp:Parameter Name="OAge" Type="Int32" />
<asp:Parameter Name="OYields" Type="String" />
<asp:Parameter Name="OPlantDate" Type="String" />
<asp:Parameter Name="OPlantFrom" Type="String" />
<asp:Parameter Name="OTreeSpacing" Type="String" />
<asp:Parameter Name="OFertilizingTimes" Type="String" />
<asp:Parameter Name="OPruningTimes" Type="String" />
<asp:Parameter Name="OWateringNeeds" Type="String" />
<asp:Parameter Name="OPollination" Type="String" />
<asp:Parameter Name="OFertilizer" Type="String" />
<asp:Parameter Name="OPesticide" Type="String" />
<asp:Parameter Name="OUserOrchardID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="dsTypeName" runat="server" ConnectionString="<%$ ConnectionStrings:DB_9DE518_PermacultureConnectionString %>" SelectCommand="SELECT * FROM [tblOrchardType]"></asp:SqlDataSource>
</asp:Content>
I'm not sure what to put in the aspx.cs file but here's what I have so far concerning the Insert button:
public void lbInsert_Click(object sender, EventArgs e)
{
dsOrchardDatabase.InsertParameters["OTypeName"].DefaultValue =
((DropDownList)gvOrchardData.FooterRow.FindControl("ddlTypeName")).SelectedItem.ToString();
dsOrchardDatabase.InsertParameters["OSpecies"].DefaultValue =
((DropDownList)gvOrchardData.FooterRow.FindControl("ddlSpecies")).SelectedItem.ToString();
dsOrchardDatabase.InsertParameters["OVariety"].DefaultValue =
((DropDownList)gvOrchardData.FooterRow.FindControl("ddlVariety")).SelectedItem.ToString();
dsOrchardDatabase.InsertParameters["OAge"].DefaultValue =
((TextBox)gvOrchardData.FooterRow.FindControl("txtBxAge")).Text;
dsOrchardDatabase.InsertParameters["OYields"].DefaultValue =
((TextBox)gvOrchardData.FooterRow.FindControl("txtBxYields")).Text;
dsOrchardDatabase.InsertParameters["OPlantDate"].DefaultValue =
((TextBox)gvOrchardData.FooterRow.FindControl("txtBxPlantDate")).Text;
dsOrchardDatabase.InsertParameters["OPlantFrom"].DefaultValue =
((TextBox)gvOrchardData.FooterRow.FindControl("txtBxPlantFrom")).Text;
dsOrchardDatabase.InsertParameters["OTreeSpacing"].DefaultValue =
((Label)gvOrchardData.FooterRow.FindControl("lblTreeSpacing")).Text;
dsOrchardDatabase.InsertParameters["OFertilizingTimes"].DefaultValue =
((Label)gvOrchardData.FooterRow.FindControl("lblFertilizingTimes")).Text;
dsOrchardDatabase.InsertParameters["OWateringNeeds"].DefaultValue =
((Label)gvOrchardData.FooterRow.FindControl("lblWateringNeeds")).Text;
dsOrchardDatabase.InsertParameters["OPollination"].DefaultValue =
((Label)gvOrchardData.FooterRow.FindControl("lblPollination")).Text;
dsOrchardDatabase.InsertParameters["OFertilizer"].DefaultValue =
((Label)gvOrchardData.FooterRow.FindControl("lblFertilizer")).Text;
dsOrchardDatabase.InsertParameters["OPesticide"].DefaultValue =
((Label)gvOrchardData.FooterRow.FindControl("lblPesticide")).Text;
dsOrchardDatabase.Insert();
}
Any help would be much appreciated!
Example of Orchard Gridview
Just to give you an idea, you should handle this on your code-behind (I noticed that the AutoPostBack property is set to true)..
Let's say on ddl1 value change event or similar:
var ddl1Value = ddl1.SelectedValue;
ddl2.ItemSource = ddl2DS.Where(item => item.Field1 = ddl1Value);
ddl3.ItemSource = ddl3DS.Where(item => item.Field1 = ddl1Value);
Basically you will just filter the item source of the other drop down lists as the value of your first drop down changes.
If you want you can also use javascript to perform this exact same concept to avoid postbacks.
give a man a fish and you feed him for a day; teach a man to fish and
you feed him for a lifetime
Here is the solution I found to work:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Configuration;
namespace PermacultureOrganizer
{
public partial class OrchardMainWebForm : System.Web.UI.Page
{
//Make the SQL connections
SqlConnection con2 = new SqlConnection(#"Data Source=SQL5018.SmarterASP.net;Initial Catalog=DB_9DE518_Permaculture;Persist Security Info=True;User ID=DB_9DE518_Permaculture_admin;Password=*****");
public string con = WebConfigurationManager.ConnectionStrings["PermaCultureConnection"].ConnectionString;
public void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Create EventHandlers
LinkButton btnInsert = new LinkButton();
btnInsert.Click += new EventHandler(btnInsert_Click);
DropDownList ddlTypeName = new DropDownList();
ddlTypeName.SelectedIndexChanged += new EventHandler(ddlTypeName_SelectedIndexChanged);
DropDownList ddlSpecies = new DropDownList();
ddlSpecies.SelectedIndexChanged += new EventHandler(ddlSpecies_SelectedIndexChanged);
DropDownList ddlVariety = new DropDownList();
ddlVariety.SelectedIndexChanged += new EventHandler(ddlVariety_SelectedIndexChanged);
}
}
protected void btnViewData_Click(object sender, EventArgs e)
{
//Go to OrchardViewer Page
Response.Redirect("OrchardViewer.aspx");
}
protected void btnSearchData_Click(object sender, EventArgs e)
{
//Go to OrchardSearch Page
Response.Redirect("OrchardSearch.aspx");
}
protected void ddlTypeName_SelectedIndexChanged(object sender, EventArgs e)
{
//Populate ddlSpecies based on TypeName selection
ddlSpecies.DataSource = RetrieveSpecies(ddlTypeName.SelectedValue);
ddlSpecies.DataBind();
ddlSpecies.Items.Insert(0, "Select Species");
}
private DataTable RetrieveSpecies(string OrchardTypeID)
{
//Use OrchardTypeID from TypeName selection to filter Species
string connString = ConfigurationManager.ConnectionStrings["PermaCultureConnection"].ConnectionString;
string sql = #"SELECT OrchardItemID, OSpecies FROM tblOrchardItem WHERE OrchardTypeID = " + OrchardTypeID;
DataTable dtSpecies = new DataTable();
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
//Initialize command object
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
//Fill the result set
adapter.Fill(dtSpecies);
}
}
return dtSpecies;
}
protected void ddlSpecies_SelectedIndexChanged(object sender, EventArgs e)
{
//Populate ddlVariety based on Species selection
ddlVariety.DataSource = RetrieveVariety(ddlSpecies.SelectedValue);
ddlVariety.DataBind();
ddlVariety.Items.Insert(0, "Select Variety");
}
private DataTable RetrieveVariety(string OrchardItemID)
{
//Use OrchardTypeID from Species selection to filter Variety
string connString = ConfigurationManager.ConnectionStrings["PermaCultureConnection"].ConnectionString;
string sql = #"SELECT OrchardItemID, OVariety FROM tblOrchardItem WHERE OrchardItemID = " + OrchardItemID;
DataTable dtVariety = new DataTable();
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
//Initialize command object
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
//Fill the result set
adapter.Fill(dtVariety);
}
}
return dtVariety;
}
protected void ddlVariety_SelectedIndexChanged(object sender, EventArgs e)
{
//Gather additional data based on Variety selection
int OrchardItemID = Convert.ToInt32(ddlVariety.SelectedIndex);
BindOrchardGrid(OrchardItemID);
//Display picture next based on Variety selection
string Variety = ddlVariety.SelectedItem.ToString();
switch (Variety)
{
case "Bladen":
imageTree.ImageUrl = "Images/blueberry-vine 300x200.jpg";
break;
case "Bartlett":
imageTree.ImageUrl = "Images/Pear-Tree 300x200.jpg";
break;
case "Babcook":
imageTree.ImageUrl = "Images/peach-tree-w-fruit 300x200.jpg";
break;
case "Abbuoto":
imageTree.ImageUrl = "Images/grape-vine 300x200.jpg";
break;
case "Carya":
imageTree.ImageUrl = "Images/pecans 300x200.jpg";
break;
}
}
private void BindOrchardGrid(int OrchardItemID)
{
DataSet dtLabels;
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SELECT * FROM tblOrchardItem WHERE OrchardItemID = " + OrchardItemID, con2);
sda.SelectCommand = cmd;
dtLabels = new DataSet("OrchardItem");
sda.Fill(dtLabels, "OrchardItem");
foreach (DataRow row in dtLabels.Tables["OrchardItem"].Rows)
{
//Gather other pertinent data based on Variety selected
lblTreeSpacing.Text = Convert.ToString(row["OTreeSpacing"]);
lblFertilizingTimes.Text = Convert.ToString(row["OFertilizingTimes"]);
lblPruningTimes.Text = Convert.ToString(row["OPruningTimes"]);
lblWateringNeeds.Text = Convert.ToString(row["OWateringNeeds"]);
lblPollination.Text = Convert.ToString(row["OPollination"]);
int FertilizerID = Convert.ToInt32(row["FertilizerID"]);
int PesticideID = Convert.ToInt32(row["PesticideID"]);
DataSet dtFert;
SqlDataAdapter sdaF = new SqlDataAdapter();
SqlCommand cmdF = new SqlCommand("SELECT * FROM tblFertilizer WHERE FertilizerID = " + FertilizerID, con2);
sdaF.SelectCommand = cmdF;
dtFert = new DataSet("Fert");
sdaF.Fill(dtFert, "Fert");
foreach (DataRow rowF in dtFert.Tables["Fert"].Rows)
{
lblFertilizer.Text = Convert.ToString(rowF["FertilizerName"]);
}
DataSet dtPest;
SqlDataAdapter sdaP = new SqlDataAdapter();
SqlCommand cmdP = new SqlCommand("SELECT * FROM tblPesticide WHERE PesticideID = " + PesticideID, con2);
sdaP.SelectCommand = cmdP;
dtPest = new DataSet("Pest");
sdaP.Fill(dtPest, "Pest");
foreach (DataRow rowP in dtPest.Tables["Pest"].Rows)
{
lblPesticide.Text = Convert.ToString(rowP["PesticideName"]);
}
}
}
public void btnInsert_Click(object sender, EventArgs e)
{
//After the user inputs data, insert it into the database and then switch to OrchardViewer page
CreateOrchard(con);
Response.Redirect("OrchardViewer.aspx");
}
public DataTable CreateOrchard(string con)
{
DataTable dtOrchard = new DataTable();
using (SqlConnection Connection = new SqlConnection(con))
{
SqlCommand sqlcmd = new SqlCommand();
//associate command object with connection
sqlcmd.Connection = Connection;
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = "spInsertOrchardData";
//Gather user input for insert into database
sqlcmd.Parameters.Add("#UserOrchardID", SqlDbType.VarChar, 1000).Value = "";
sqlcmd.Parameters.Add("#TypeName", SqlDbType.VarChar, 1000).Value = Convert.ToString(ddlTypeName.SelectedItem);
sqlcmd.Parameters.Add("#Species", SqlDbType.VarChar, 1000).Value = Convert.ToString(ddlSpecies.SelectedItem);
sqlcmd.Parameters.Add("#Variety", SqlDbType.VarChar, 1000).Value = Convert.ToString(ddlVariety.SelectedItem);
sqlcmd.Parameters.Add("#Age", SqlDbType.Int, 1000).Value = Convert.ToInt32(txtBxAge.Text);
sqlcmd.Parameters.Add("#Yields", SqlDbType.VarChar, 1000).Value = Convert.ToInt32(txtBxYields.Text);
sqlcmd.Parameters.Add("#PlantDate", SqlDbType.VarChar, 1000).Value = Convert.ToString(txtBxPlantDate.Text);
sqlcmd.Parameters.Add("#PlantFrom", SqlDbType.VarChar, 1000).Value = Convert.ToString(txtBxPlantFrom.Text);
sqlcmd.Parameters.Add("#TreeSpacing", SqlDbType.VarChar, 1000).Value = Convert.ToString(lblTreeSpacing.Text);
sqlcmd.Parameters.Add("#FertilizingTimes", SqlDbType.VarChar, 1000).Value = Convert.ToString(lblFertilizingTimes.Text);
sqlcmd.Parameters.Add("#PruningTimes", SqlDbType.VarChar, 1000).Value = Convert.ToString(lblPruningTimes.Text);
sqlcmd.Parameters.Add("#WateringNeeds", SqlDbType.VarChar, 1000).Value = Convert.ToString(lblWateringNeeds.Text);
sqlcmd.Parameters.Add("#Pollination", SqlDbType.VarChar, 1000).Value = Convert.ToString(lblPollination.Text);
sqlcmd.Parameters.Add("#Fertilizer", SqlDbType.VarChar, 1000).Value = Convert.ToString(lblFertilizer.Text);
sqlcmd.Parameters.Add("#Pesticide", SqlDbType.VarChar, 1000).Value = Convert.ToString(lblPesticide.Text);
using (SqlDataAdapter sda = new SqlDataAdapter(sqlcmd))
{
DataSet dataset = new DataSet();
sda.Fill(dataset);
}
}
return dtOrchard;
}
}
}

Automatically create labels based on the number of database entry's c# asp.net mssql

Is there a way to generate labels based on how many user entry's there are in a database and print the database information to the labels on page load.
I have attempted to do this by binding the data but i found i can only do this in a grid format and i don't want a grid.
What i am trying to create overall is a survey in which the questions are stored in the database and displayed on the labels. I want someone to be able to add a question to the database and a label to be automatically generated for it displaying the question.
I am able to get my desired effect but i have added labels and written the questions on them manually. If anyone can please help or advise if it can be done it would be much appreciated. Thank you in advanced.
Here is what i have so far:
<h1> </h1>
<h1>PaaS Assured Server Test</h1>
<div class="row">
<div class="col-md-6">
<h2>
<asp:Label ID="lblmsg" runat="server"></asp:Label>
<asp:Panel ID="BugPanel1" runat="server" BorderColor="#FFFF99" BackColor="#FFFF99" Visible="False">
<asp:Label ID="Label4" runat="server" Text="You have informed us of an error." ForeColor="Black"></asp:Label>
<br /><asp:Label ID="Label3" runat="server" Text="Please advise of serverity. 1 - highest 5 - lowest:" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="SeverityList1" runat="server" AutoPostBack="True">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
</asp:DropDownList>
<br /><asp:Label ID="Label5" runat="server" Text="Who shall be notified of the error:" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="NotifyList1" runat="server" DataSourceID="SqlDataSource2" AutoPostBack="True">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT [UserName] FROM [AspNetUsers]"></asp:SqlDataSource>
<br /><asp:Label ID="Label6" runat="server" Text="Would you like a copy emailed to yourself?" ForeColor="Black"></asp:Label>
<asp:RadioButtonList ID="EmailRadio1" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
<asp:ListItem Value="True" Text="Yes">Yes</asp:ListItem>
<asp:ListItem Value="True" Text="Yes">No</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="BugButton" runat="server" Text="File Bug and Generate Report" CausesValidation="False" OnClick="BugButton_Click" />
</asp:Panel>
</h2>
<h2>Provisioning</h2>
<hr />
<asp:Panel ID="FormPanel1" runat="server" BackColor="#F4F4F4">
<asp:Panel ID="HeadPanel1" runat="server" BackColor="#E4E4E4" BorderColor="#999999" Font-Bold="True" ForeColor="#000066" Font-Underline="True">
<h3>Page View</h3>
</asp:Panel>
<asp:RequiredFieldValidator ID="Radio1Validator" runat="server" ErrorMessage="Error: Please select an option:" ControlToValidate="Radio1" SetFocusOnError="True" ForeColor="Red"></asp:RequiredFieldValidator>
<p />
<asp:Label ID="PALabel1" runat="server" Text="Does your screen look similar to the image displayed ?"></asp:Label>
<asp:ImageButton ID="ImageButton1" runat="server" Height="20px" ImageUrl="~/Image/PrintScreen/Info.jpg" OnClick="ImageButton1_Click" Width="21px" CausesValidation="False" /><br/>
<asp:RadioButtonList ID="Radio1" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
<asp:ListItem Value="True" Text="Yes">Yes</asp:ListItem>
<asp:ListItem Text="No" Value="False">No</asp:ListItem>
</asp:RadioButtonList>
<asp:Panel ID="PAPanel1" runat="server">
<asp:Label ID="Label1" runat="server" ForeColor="#000099" Text="Provide further details:"></asp:Label>
<asp:TextBox ID="PAText1" runat="server" BorderColor="Silver" CssClass="form-control"></asp:TextBox>
</asp:Panel>
<p />
<asp:RequiredFieldValidator ID="Radio2Validator" runat="server" ControlToValidate="Radio2" ErrorMessage="Error: Please select an option:" ForeColor="Red"></asp:RequiredFieldValidator>
<p />
<asp:Label ID="PALabel2" runat="server" Text="In "Server Name" is virtual pre-selected?"></asp:Label>
<asp:ImageButton ID="ImageButton4" height="20px" runat="server" Width="21px" CausesValidation="False" ImageUrl="~/Image/PrintScreen/Info.jpg" OnClick="ImageButton4_Click" />
<br/>
<asp:RadioButtonList ID="Radio2" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
<asp:ListItem Value="True" Text="Yes">Yes</asp:ListItem>
<asp:ListItem Text="No" Value="False">No</asp:ListItem>
</asp:RadioButtonList>
<asp:Panel ID="PAPanel2" runat="server">
<asp:Label ID="Label2" runat="server" Text="Provide further details:" ForeColor="#000099"></asp:Label>
<asp:TextBox ID="PAText2" runat="server" CssClass="form-control" BorderColor="Silver" ></asp:TextBox>
</asp:Panel>
<asp:Panel ID="HeadPanel2" runat="server" BackColor="#E4E4E4" BorderColor="#999999" Font-Bold="True" ForeColor="#000066" Font-Underline="True">
<h3>Form details</h3>
</asp:Panel>
<asp:Panel ID="SubHead1" runat="server" BackColor="#F3F3F3" BorderColor="#999999" Font-Bold="False" ForeColor="#003399" Font-Underline="True" Font-Italic="True" Font-Size="Smaller">
<h4>Request Details</h4>
</asp:Panel>
<asp:Panel ID="SubHead2" runat="server" BackColor="#F3F3F3" BorderColor="#999999" Font-Bold="False" ForeColor="#003399" Font-Underline="True" Font-Italic="True" Font-Size="Smaller">
<h4>Server Location</h4>
</asp:Panel>
<asp:Panel ID="SubHead3" runat="server" BackColor="#F3F3F3" BorderColor="#999999" Font-Bold="False" ForeColor="#003399" Font-Underline="True" Font-Italic="True" Font-Size="Smaller">
<h4>Product and Support Details</h4>
</asp:Panel>
<asp:Panel ID="SubHead4" runat="server" BackColor="#F3F3F3" BorderColor="#999999" Font-Bold="False" ForeColor="#003399" Font-Underline="True" Font-Italic="True" Font-Size="Smaller">
<h4>Server Configuration</h4>
</asp:Panel>
<asp:Label ID="PALabel3" runat="server" Text="What operating system are you testing?"></asp:Label>
<asp:ImageButton ID="ImageButton3" runat="server" Height="20px" ImageUrl="~/Image/PrintScreen/Info.jpg" OnClick="ImageButton1_Click" Width="21px" CausesValidation="False" /><br/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please select the server you are testing:" ControlToValidate="Radio3" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RadioButtonList ID="Radio3" runat="server" AutoPostBack="True" RepeatDirection="Horizontal">
<asp:ListItem Value="Windows 2008 Server R2" Text="Windows 2008 Server R2">Windows 2008 Server R2</asp:ListItem>
<asp:ListItem Value="Windows 2012 Server R2" Text="Windows 2012 Server R2">Windows 2012 Server R2</asp:ListItem>
<asp:ListItem Value="RHEL" Text="RHEL">RHEL</asp:ListItem>
</asp:RadioButtonList>
<p /> <p />
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Submit"/>
<p />
</asp:Panel>
</div>
<div class="col-md-6">
<h2> </h2>
<h2>Information Viewer <asp:Image ID="LrgInfoImage" runat="server" ImageUrl="~/Image/PrintScreen/Info.jpg" Height="21px" Width="24px" />
&nbsp&nbsp<asp:Button ID="Button2" runat="server" Text="View test history" BorderColor="#ECECFF" BorderStyle="Ridge" CssClass="btn" Font-Underline="True" ForeColor="#0066FF" Height="32px" OnClick="Button2_Click" Width="177px" CausesValidation="False" />
</h2> <hr />
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View0" runat="server">
<div style="overflow-x:auto;width:600px" class="fixed">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="PAssuredId" DataSourceID="SqlDataSource1" AllowSorting="True" BorderColor="#F4F4F4" ForeColor="#000066" GridLines="Horizontal" Width="56%" HorizontalAlign="Center">
<AlternatingRowStyle BackColor="#F4F4FF" BorderColor="Black" ForeColor="#000066" />
<Columns>
<asp:BoundField DataField="PAssuredId" HeaderText="Test ID" InsertVisible="False" ReadOnly="True" SortExpression="PAssuredId" NullDisplayText="INVALID TEST" ItemStyle-BackColor="#F0F0FF" />
<asp:BoundField DataField="Date" HeaderText="Date/ Time" SortExpression="Date" />
<asp:BoundField DataField="UserName" HeaderText="User" SortExpression="UserName" NullDisplayText="INVALID TEST" />
<asp:BoundField DataField="Platform" HeaderText="Platform" SortExpression="Platform" NullDisplayText="User did not select platform" />
<asp:CheckBoxField DataField="VirtualPreselect" HeaderText="Virtual" SortExpression="VirtualPreselect" />
<asp:CheckBoxField DataField="DetsAccurate" HeaderText="Details ok?" SortExpression="DetsAccurate" />
<asp:CheckBoxField DataField="ScreenSame" HeaderText="Correct form?" SortExpression="ScreenSame" />
<asp:BoundField DataField="No1" HeaderText="Error 1" SortExpression="No1" NullDisplayText="No error found" ReadOnly="True" />
<asp:BoundField DataField="No2" HeaderText="Error 2" SortExpression="No2" NullDisplayText="No error found" />
<asp:BoundField DataField="No3" HeaderText="Error 3" SortExpression="No3" NullDisplayText="No error found" />
<asp:BoundField DataField="No4" HeaderText="Error 4" SortExpression="No4" NullDisplayText="No error found" />
<asp:BoundField DataField="No5" HeaderText="Error 5" SortExpression="No5" NullDisplayText="No error found" />
</Columns>
</asp:GridView>
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT PaaSAssuredServer.PAssuredId, PaaSAssuredServer.Date, AspNetUsers.UserName, PaaSAssuredServer.Platform, PaaSAssuredServer.VirtualPreselect, PaaSAssuredServer.DetsAccurate, PaaSAssuredServer.ScreenSame, PaaSAssuredServer.No1, PaaSAssuredServer.No2, PaaSAssuredServer.No3, PaaSAssuredServer.No4, PaaSAssuredServer.No5 FROM PaaSAssuredServer INNER JOIN AspNetUsers ON PaaSAssuredServer.UserId = AspNetUsers.Id ORDER BY PaaSAssuredServer.Date DESC"></asp:SqlDataSource>
</asp:View>
<asp:View ID="View1" runat="server">
<asp:Image ID="ScreenImge" runat="server" Height="600px" ImageUrl="~/Image/PrintScreen/PassTest1.jpg" Width="600px" />
</asp:View>
<asp:View ID="View2" runat="server">
<asp:Image ID="Image1" runat="server" Height="105px" ImageUrl="~/Image/PrintScreen/ServerType.jpg" Width="446px" />
</asp:View>
<asp:View ID="View3" runat="server">
<asp:Image ID="Image2" runat="server" ImageUrl="~/Image/PrintScreen/ServerType.jpg" Height="105px" Width="446px" />
</asp:View>
</asp:MultiView>
</div>
</div>
</asp:Content>
Here is the code behind :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Windows.Forms;
using Microsoft.AspNet.Identity;
namespace IRISTest
{
public partial class PaaSAssuredServer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Radio1.SelectedValue == "False")
{
PAPanel1.Visible = true;
}
else
{
PAPanel1.Visible = false;
}
if (Radio2.SelectedValue == "False")
{
PAPanel2.Visible = true;
}
else
{
PAPanel2.Visible = false;
}
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
MultiView1.ActiveViewIndex = 1;
}
protected void Button2_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 0;
}
protected void ImageButton4_Click(object sender, ImageClickEventArgs e)
{
MultiView1.ActiveViewIndex = 3;
}
protected void Submit(object sender, EventArgs e)
{
{
string message = "I can confirm the following:" + Environment.NewLine + "It is " + Radio1.SelectedValue + " that my screen matches that displayed in the image. " + Environment.NewLine +
"It is:" + Radio2.SelectedValue + " that my default Server Name is set to Virtual. " + Environment.NewLine +
"I have follwed the steps accurately and provided all requested information/ further details to enable further investigation" + Environment.NewLine +
"On hitting sumbit I am confirming that I have perfomed this test and the provided information is accurate to my knowledge.";
string caption = "Confirmation:";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
MessageBoxIcon icon = MessageBoxIcon.Information;
MessageBoxDefaultButton defaultbutton = MessageBoxDefaultButton.Button2;
DialogResult result;
result = MessageBox.Show(message, caption, buttons, icon, defaultbutton);
if (result == DialogResult.Yes)
{
Int32 newProdID = 0;
var userId = User.Identity.GetUserId();
var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO [PaaSAssuredServer] ([VirtualPreselect], [No1], [No2], [ScreenSame], [Date], [UserId], [Platform]) VALUES ( #VirtualPreselect, #No1, #No2, #ScreenSame, #Date, #UserId, #Platform);" + "SELECT CAST(scope_identity() AS int)");
//cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#ScreenSame", Radio1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#VirtualPreselect", Radio2.SelectedItem.Value);
cmd.Parameters.AddWithValue("#No1", PAText1.Text);
cmd.Parameters.AddWithValue("#No2", PAText2.Text);
cmd.Parameters.AddWithValue("#Date", DateTime.Now);
cmd.Parameters.AddWithValue("#UserId", userId);
cmd.Parameters.AddWithValue("#Platform", Radio3.SelectedItem.Value);
//cmd.Parameters.AddWithValue("#UserId", 0);
//cmd.Parameters["#UserId"].Direction = ParameterDirection.InputOutput;
connection.Open();
try
{
newProdID = (Int32)cmd.ExecuteScalar();
//int UserId = (int)cmd.Parameters["#UserId"].Value;
//cmd.ExecuteNonQuery();
//var rowCount = cmd.ExecuteScalar();
lblmsg.Text = "You have completed and recorded the test Sucessfully " + Environment.NewLine +
"Your test number is: " + newProdID;
lblmsg.ForeColor = System.Drawing.Color.Green;
}
catch (SqlException sqlEx)
{
lblmsg.Text = sqlEx.Message;
lblmsg.ForeColor = System.Drawing.Color.Red;
}
finally
{
connection.Close();
}
if (PAText1.Text == "0")
{
BugPanel1.Visible = true;
}
else
{
BugPanel1.Visible = false;
}
if (PAText2.Text == "0")
{
BugPanel1.Visible = true;
}
else
{
BugPanel1.Visible = false;
}
}
}
}
}
protected void BugButton_Click(object sender, EventArgs e)
{
Int32 newProdID1 = 0;
var userId = User.Identity.GetUserId();
var BugTest = true;
var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO [BugRep] ([Bug], [Serverity], [CorrName], [UserId]) VALUES (#Bug, #Serverity, #CorrName, #UserId);" + "SELECT CAST(scope_identity() AS int)");
//cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Serverity", SeverityList1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#CorrName", NotifyList1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Bug", BugTest);
cmd.Parameters.AddWithValue("#UserId", userId);
cmd.Parameters.AddWithValue("#Platform", Radio3.SelectedItem.Value);
//cmd.Parameters.AddWithValue("#UserId", 0);
//cmd.Parameters["#UserId"].Direction = ParameterDirection.InputOutput;
connection.Open();
try
{
newProdID1 = (Int32)cmd.ExecuteScalar();
//int UserId = (int)cmd.Parameters["#UserId"].Value;
//cmd.ExecuteNonQuery();
//var rowCount = cmd.ExecuteScalar();
lblmsg.Text = "You have reported the bug sucessfully and" + NotifyList1.SelectedItem.Value + "has been informed." + Environment.NewLine +
"Your test number is: " + newProdID1;
lblmsg.ForeColor = System.Drawing.Color.Green;
}
catch (SqlException sqlEx)
{
lblmsg.Text = sqlEx.Message;
lblmsg.ForeColor = System.Drawing.Color.Red;
}
finally
{
connection.Close();
}
}
}
}
}
You are on the right track to use data binding. If you want to have more control over the HTML that is generated, you can use a Repeater control. This way, you can specify templates for the items you want to display.
The following sample shows a Repeater. In the ItemTemplate, a HiddenField stores the question id and a Label shows the text. When the page is requested, the items are retrieved from a database (the sample uses test data) and bound to the Repeater. I've also added a dropdown in the ItemTemplate so that the user can select an answer. Upon clicking the Save button, the values are retrieved from the controls in the items of the Repeater.
ASPX
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<p>
<asp:HiddenField ID="hiddenId" runat="server" Value='<%# Eval("Id") %>' />
<asp:Label ID="lblQuestion" runat="server" Text='<%# Eval("Text") %>' />
<asp:DropDownList ID="ddlAnswer" runat="server">
<asp:ListItem Text="1" />
<asp:ListItem Text="2" />
<asp:ListItem Text="3" />
</asp:DropDownList>
</p>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
Code Behind
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var questions = GetQuestions();
rpt.DataSource = questions;
rpt.DataBind();
}
}
private IEnumerable<Question> GetQuestions()
{
// Load questions from database
// Setting up some sample data for this sample
var lst = new List<Question>();
return Enumerable.Range(1, 5).Select(x => new Question() { Id = x, Text = "Question " + x.ToString() });
}
protected void btnSave_Click(object sender, EventArgs e)
{
var dictAnswers = GetValuesFromRepeater();
// Save answers to database
}
private IDictionary<int, int> GetValuesFromRepeater()
{
var dict = new Dictionary<int, int>();
foreach (RepeaterItem item in rpt.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
var id = int.Parse(((HiddenField)item.FindControl("hiddenId")).Value);
var answer = int.Parse(((DropDownList)item.FindControl("ddlAnswer")).Text);
dict.Add(id, answer);
}
}
return dict;
}
}
public class Question
{
public int Id { get; set; }
public string Text { get; set; }
}
Please note that when retrieving the values from the repeater, the controls have to be found by their id using the FindControl method.
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand ("select fields from database", con);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
foreach (DataRow dr in DataSet.Tables[0].Rows){
Label lbl = new Label();
lbl.Text = dr["column"].ToString() + ":";
TextBox txt = new TextBox();
txt.ID = "txt" + dr["id"].ToString();
}
You have to push it into !IsPostBack
On saving you have to take all IDs into some array or list, and use foreach array:
foreach (int id in id_array){
command.Parameters.AddWithValue("#"+param+id.ToString(), (TextBox)(Page.FindControlById("txt"+id.ToString())).Text);
}
But you also have to think about your sql_query (in code-behind or stored procedure, make it responsive, depending on params number).
Hope it helps

Visual Studio 12 - Gridview inserting footer row on submit

I have a gridview that I need a footer row inserted with the data from a textbox when the user hits submit. I have tried over and over and I can not get past the following error:
Object reference not set to an instance of an object. The error is flagged on the Textbox AddName line of code in the code behind.
Here is my code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Admin.aspx.cs" Inherits="WorkOrder.Admin" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="Style.css" rel="stylesheet" type="text/css" />
<link href="msgBoxLight.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.msgBox.js" type="text/javascript"></script>
</head>
<body>
<form id="form2" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" Width="1020px">
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/mast_left.png" />
</asp:Panel>
</div>
<div class="Section"> <hr /><h2>
Online Work Order Form - (Admin)</h2>
</div>
<br />
<asp:Label ID="Label2" runat="server" Text="Select data you want to view and click the submit button:" CssClass="label"></asp:Label><br /><br />
<div>
<asp:GridView ID="GridViewAdmin" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataSourceID="SqlDataSource1" DataKeyNames="WO_ID" EnableModelValidation="True"
>
<Columns>
<asp:BoundField DataField="WO_ID" HeaderText="WO_ID" ReadOnly="True" SortExpression="WO_ID" />
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="Name" />
<asp:BoundField DataField="Job_Title" HeaderText="Job_Title" ReadOnly="True" SortExpression="Job_Title" />
<asp:BoundField DataField="Job_Assigned_To" HeaderText="Job_Assigned_To" SortExpression="Job_Assigned_To" />
<asp:CheckBoxField DataField="Completed" HeaderText="Completed" SortExpression="Completed" />
<asp:BoundField DataField="Completed_Date" HeaderText="Completed_Date" SortExpression="Completed_Date" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ZSC_WorkOrdersConnectionString %>"
SelectCommand="SELECT [WO_ID], [Name], [Job_Type], [Job_UpdateName], [Job_Title], [Job_Description], [Job_Assigned_To], [Completed], [Completed_Date], [Notes] FROM [WO_Submission_Details]"
UpdateCommand="UPDATE [WO_Submission_Details] SET [Job_Assigned_To] = #Job_Assigned_To, [Completed] = #Completed, [Completed_Date] = #Completed_Date, [Notes] = #Notes WHERE [WO_ID] = #WO_ID">
</asp:SqlDataSource>
</div>
<br /> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/AdminReport.aspx">Work Order Report</asp:HyperLink>
<br />
<br />
<hr />
<br />
<asp:Label ID="Label1" runat="server" Text="Enter name below to add to Marketing employee table" CssClass="label"></asp:Label>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Name:" CssClass="label"></asp:Label>
<asp:TextBox ID="txtAddName" runat="server" Width="170px"></asp:TextBox><br /><br />
<asp:Label ID="Label4" runat="server" Text="Email:" CssClass="label"></asp:Label>
<asp:TextBox ID="txtAddEmail" runat="server" Width="170px"></asp:TextBox>
<br /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
<br /><br />
<asp:GridView ID="GridViewStaff" runat="server"
AutoGenerateColumns="False"
AutoGenerateDeleteButton="True"
BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="5"
DataSourceID="SqlDataSource2" datakeynames="ID" AllowSorting="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("Name") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName" runat="server" Width="170px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" text='<%#Eval("Email")%>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddEmail" runat="server" Width="170px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ZSC_WorkOrdersConnectionString %>"
SelectCommand="SELECT * FROM [Marketing_Staff]" InsertCommand="INSERT INTO [Marketing_Staff] ([Name], [Email]) VALUES (#Name, #Email)">
<InsertParameters>
<asp:Parameter Type="String" Name="Name"></asp:Parameter>
<asp:Parameter Type="String" Name="Email"></asp:Parameter>
</InsertParameters>
</asp:SqlDataSource>
</form>
</body>
</html>
Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Design;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Text;
using System.IO;
namespace WorkOrder
{
public partial class Admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
bindgridView();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
TextBox AddName = GridViewStaff.FooterRow.FindControl("txtAddName") as TextBox;
// Response.Write(AddName.Text);
//TextBox Email = GridViewStaff.FooterRow.FindControl("txtAddEmail") as TextBox;
SqlDataSource2.InsertParameters["Name"].DefaultValue = txtAddName.Text;
// SqlDataSource2.InsertParameters["Email"].DefaultValue = txtAddEmail.Text;
SqlDataSource2.Insert();
// ExecuteInsert(txtAddName.Text);
txtAddName.Text = "";
txtAddEmail.Text = "";
}
public string GetConnectionString()
{
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["ZSC_WorkOrdersConnectionString"].ConnectionString;
}
public void bindgridView()
{
try
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string query = "Select * WO_ID, Name, Job_Type, Job_UpdateName, Job_Title, Job_Description, Job_Assigned_To, Completed, Completed_Date, Notes FROM WO_Submission_Details";
DataSet ds = new DataSet();
SqlDataAdapter sqldt = new SqlDataAdapter(query, conn);
sqldt.Fill(ds);
GridViewAdmin.DataSource = ds;
GridViewAdmin.DataBind();
if (ViewState["delRows"] != null)
{
int[] delIndices = (int[])ViewState["delRows"];
int itemsLength = delIndices.Count(indx => indx != 0);
//create the javascript array in the client side
//push the deleted row indexes from c# array to javascript array
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("var indexArray = new Array;");
for (int i = 0; i < itemsLength; i++)
{
sb.Append("indexArray.push('" + delIndices[i] + "');");
}
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "arrayScript", sb.ToString());
//call the deleteRow function on the client side
this.ClientScript.RegisterStartupScript(typeof(Page), "del", "javascript:deletegrdvwRow()", true);
}
}
catch (Exception)
{ }
}
protected void GridViewAdmin_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewAdmin.EditIndex = e.NewEditIndex;
}
protected void GridViewAdmin_RowCancelingEdit(object sender, EventArgs e)
{
GridViewAdmin.EditIndex = -1;
}
protected void GridViewAdmin_RowCreated(object sender, GridViewRowEventArgs e)
{
foreach (TableCell cell in e.Row.Cells)
{
if (!string.IsNullOrEmpty(cell.Text) && cell.Text != " ")
{
BoundField field = (BoundField)((DataControlFieldCell)cell).ContainingField;
if ((field.DataField != "Job_Assigned_To") && (field.DataField != "Completed") && (field.DataField != "Completed_Date") && (field.DataField != "Notes"))
field.ReadOnly = true;
}
}
}
protected void GridViewAdmin_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
GridViewAdmin.PageIndex = e.NewPageIndex;
//while moving to the next page, clear the viewstate
ViewState["delRows"] = null;
}
catch (Exception)
{ }
}
protected void GridViewAdmin_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
GridViewRow row = (GridViewRow)GridViewAdmin.Rows[e.RowIndex];
//i set datakeys="ProductName,ProductID" in gridview in aspx page
//datakeys[rowindex][1]->refers to productid which is primary key.
string WOID = GridViewAdmin.DataKeys[row.RowIndex][0].ToString();
SqlConnection conn = new SqlConnection(GetConnectionString());
TextBox JobAssignedTo = (TextBox)row.FindControl("txtJobAssignedTo");
CheckBox txtCompleted = (CheckBox)row.Cells[1].Controls[0];
TextBox CompletedDate = (TextBox)row.Cells[2].Controls[0];
TextBox Notes = (TextBox)row.Cells[3].Controls[0];
//write your logic here to update the data into the database
conn.Open();
SqlCommand cmd = new SqlCommand("update WO_Submission_Details set Job_Assigned_To='" + JobAssignedTo.Text + "',Completed='" + txtCompleted.Checked + "',Completed_Date='" + CompletedDate.Text + "',Notes='" + Notes.Text + "'where WO_ID='" + WOID + "'", conn);
//SqlCommand cmd = new SqlCommand("update duplicating_request_table set Completed_By=#CompletedBy WHERE Job_No=#JobNo");
cmd.ExecuteNonQuery();
conn.Close();
GridViewAdmin.EditIndex = -1;
//those rows which are deleted previously while updating store it's indexs
if (ViewState["delRows"] == null)
{
int[] delIndices = new int[12];
delIndices[0] = e.RowIndex;
ViewState["delRows"] = delIndices;
}
else
{
int[] delIndices = (int[])ViewState["delRows"];
int itemsLength = delIndices.Count(indx => indx != 0);
delIndices[itemsLength] = e.RowIndex;
}
}
catch (Exception exc)
{
Console.WriteLine(exc);
}
}
}
}
It looks like your SqlDataSource2 is causing the error. Please double check that both Name and Email are of DB type string in your DB.
In your ASPX SqlDataSource2 make the following changes:
<InsertParameters>
<asp:QueryStringParameter Name="Name" QueryStringField="Name" DbType=String />
<asp:QueryStringParameter Name="Email" QueryStringField="Email" DbType=String />
</InsertParameters>
In your C# Code-Behind, change to this:
SqlDataSource2.InsertParameters[0].DefaultValue = txtAddName.Text;

Categories

Resources