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;
Related
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.
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.
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" />
  <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
I am currently using Visual Studio to build my project and I'm having it automatically generate the Edit button. My Gridview allows for searching via a search box and a page only handles up to 10 rows. On the very first load of the Gridview, the Edit button and the accompanying Update and Cancel work perfectly fine. However, once I click on a new page, it fires these errors when I try to click Edit (the second error was when I somehow got the Update and Cancel button to show):
The GridView 'ProjectTable' fired event RowEditing which wasn't handled.
The GridView 'ProjectTable' fired event RowCancelingEdit which wasn't handled.
What is going on? Here is my aspx page:
<head runat="server">
<title></title>
<style>
.hiddencol
{
display: none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="SearchBox" runat="server"></asp:TextBox>
<asp:DropDownList ID="SearchParameterList" runat="server">
<asp:ListItem Selected="True" Value="Project_Name">Project Name</asp:ListItem>
<asp:ListItem Value="Product">Product</asp:ListItem>
<asp:ListItem Value="Description">Description</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="SearchButton" runat="server" Text="Search" OnClick="SearchButton_Click" />
<asp:Button ID="ClearButton" runat="server" OnClick="ClearButton_Click" Text="Clear" />
<br />
<br />
<asp:GridView ID="ProjectTable" runat="server" Font-Names="Verdana,Arial" Font-Size="12px" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataSourceID="PopulateProjectTable" AllowPaging="True" OnPageIndexChanging="ProjectTable_PageIndexChanging>
<AlternatingRowStyle BackColor="#BFE4FF" />
<PagerStyle BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
<HeaderStyle Height="30px" BackColor="#6DC2FF" Font-Size="12px" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
<RowStyle Height="20px" Font-Size="12px" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
<Columns>
<asp:BoundField DataField="ProjID" HeaderText="ProjID" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" SortExpression="ProjID" />
<asp:BoundField DataField="Project_Name" HeaderText="Project Name Value" ReadOnly="True" SortExpression="Project_Name" />
<asp:BoundField DataField="Product" HeaderText="Product" SortExpression="Product" ReadOnly="True" />
<asp:BoundField DataField="Product_Edit" HeaderText="Product (alternate)" SortExpression="Product_Edit" />
<asp:BoundField DataField="Description" HeaderText="Description" ReadOnly="True" SortExpression="Description" />
<asp:BoundField DataField="Description_Edit" HeaderText="Description (alternate)" SortExpression="Description_Edit" />
<asp:BoundField DataField="Comment" HeaderText="Comment Submission/Approval" SortExpression="Comment" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="PopulateProjectTable" runat="server"
ConnectionString="<%$ ConnectionStrings:ODSConnectionString %>"
SelectCommand="SELECT [Project_Name], [Product], [Product_Edit], [Description], [Description_Edit], [Comment], [ProjID] FROM [Pipeline_Detail]"
UpdateCommand="UPDATE [Pipeline_Detail] SET Product_Edit = #Product_Edit, Description_Edit= #Description_Edit, Comment = #Comment WHERE ProjID = #ProjID">
<UpdateParameters>
<asp:Parameter Name="ProjID"/>
<asp:Parameter Name="Product_Edit" Type="String"/>
<asp:Parameter Name="Description_Edit" Type="String"/>
<asp:Parameter Name="Comment" Type="String"/>
</UpdateParameters>
</asp:SqlDataSource>
</div>
</form>
And here is my code behind:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SearchButton_Click(object sender, EventArgs e)
{
ProjectTable.PageIndex = 0;
ProjectTable.DataSourceID = null;
PopulateProjectTable.SelectCommand = "SELECT [Project_Name], [Product], [Product_Edit], [Description], [Description_Edit], [Comment], [ProjID] FROM [Pipeline_Detail] WHERE " + SearchParameterList.SelectedValue.ToString() + " LIKE '%" + SearchBox.Text + "%'";
ProjectTable.DataSource = PopulateProjectTable;
ProjectTable.DataBind();
}
protected void ClearButton_Click(object sender, EventArgs e)
{
ProjectTable.PageIndex = 0;
ProjectTable.DataSourceID = null;
PopulateProjectTable.SelectCommand = "SELECT [Project_Name], [Product], [Product_Edit], [Description], [Description_Edit], [Comment], [ProjID] FROM [Pipeline_Detail] WHERE Project_Name LIKE '%%'";
ProjectTable.DataSource = PopulateProjectTable;
ProjectTable.DataBind();
SearchBox.Text = "";
}
protected void ProjectTable_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
ProjectTable.PageIndex = e.NewPageIndex;
ProjectTable.DataSourceID = null;
PopulateProjectTable.SelectCommand = "SELECT [Project_Name], [Product], [Product_Edit], [Description], [Description_Edit], [Comment], [ProjID] FROM [Pipeline_Detail] WHERE " + SearchParameterList.SelectedValue.ToString() + " LIKE '%" + SearchBox.Text + "%'" ;
ProjectTable.DataSource = PopulateProjectTable;
ProjectTable.DataBind();
}
}
You need to implement those events. In your markup you set auto generate edit button to true but you never implement the On Row Editing event and On Row Cancelling Edit event. Updating your markup to:
<asp:GridView ID="ProjectTable" runat="server" Font-Names="Verdana,Arial" Font-Size="12px" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataSourceID="PopulateProjectTable" AllowPaging="True" OnPageIndexChanging="ProjectTable_PageIndexChanging" OnRowEditing="ProjectTable_OnRowEditing" OnRowCancelingEdit="ProjectTable_OnRowCancellingEdit">
and then add that method to your code behind:
protected void ProjectTable_OnRowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void ProjectTable_OnRowCancellingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
i am working on Asp.Net with C#-4.0 .
I want to get Input from end user in a GridView. Like
in DropDownList or in TextBox i enters some value and clicks on Add then new record will add but previous data was lost.
the Problem is when i change value of controls, it not saves in DataTable to which it is binded. How can i save this value to DataTable. What code i have missed here ?
designer code :
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="SaleOrder.aspx.cs" Inherits="Transactions_SaleOrder" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FormHeader" Runat="Server">
<p>Sale Order</p>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="FormBody" Runat="Server">
<table class="style1">
<tr>
<td>
<asp:Label ID="lblDate" runat="server" Text="Date : "></asp:Label>
<asp:TextBox ID="txtSODate" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="txtSODate_CalendarExtender" runat="server"
Enabled="True" TargetControlID="txtSODate" Format="dd/MM/yyyy" PopupButtonID="ImageButton1">
</asp:CalendarExtender>
<asp:MaskedEditExtender ID="txtSODate_MaskedEditExtender" runat="server"
Enabled="True" Mask="99/99/9999" MaskType="Date" TargetControlID="txtSODate">
</asp:MaskedEditExtender>
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="~/images/Calendar_scheduleHS.png" />
</td>
</tr>
<tr>
<td>
Shift :
<asp:DropDownList ID="DropDownList1" runat="server" Width="300px">
<asp:ListItem Value="Morning">MORNING</asp:ListItem>
<asp:ListItem Value="EVENING"></asp:ListItem>
<asp:ListItem Value="OTHERS"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None"
onrowcommand="GridView1_RowCommand">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:DropDownList ID="ddlProduct" runat="server" Width="300"
DataSource='<%# dtProductMaster %>'
DataTextField="PDescr"
DataValueField="PID"
>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Qty">
<ItemTemplate>
<asp:TextBox ID="txtQuan" runat="server" MaxLength="5" style="text-align:right" Text='<%# BIND("QUAN") %>'></asp:TextBox>
<asp:MaskedEditExtender ID="txtQuan_MaskedEditExtender" runat="server" Enabled="True"
Mask="99999" TargetControlID="txtQuan">
</asp:MaskedEditExtender>
</ItemTemplate>
<ItemStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:ButtonField CommandName="ADD" Text="Add" />
<asp:ButtonField CommandName="DELETE" Text="Delete" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" Width="58px" />
</td>
</tr>
</table>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="FormFooter" Runat="Server">
</asp:Content>
C# Code behind it :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Transactions_SaleOrder : System.Web.UI.Page
{
internal DataTable dtProductMaster_;
internal DataTable dtProductMaster
{
get
{
if (dtProductMaster_ == null)
{
clsData d = new clsData();
d.Select("select PID, PEDESCR2 + ' ' + PEDESCR3 as PDescr From TBLPROD_MAST");
dtProductMaster_ = d.DataTable;
}
return dtProductMaster_;
}
}
DataTable dtProductDet
{
get
{
if (ViewState["dtProductDet"] != null)
{
return (DataTable)ViewState["dtProductDet"];
}
else
{
return null;
}
}
set
{
ViewState["dtProductDet"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
txtSODate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
//--
dtProductDet = new DataTable("dtProductDet");
dtProductDet.Columns.Add("PID", typeof(int));
dtProductDet.Columns.Add("PName", typeof(string));
dtProductDet.Columns.Add("Quan", typeof(decimal));
dtProductDet.Rows.Add(0,"",0);
//--
}
GridView1.DataSource = dtProductDet;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName.ToUpper())
{
case "ADD":
dtProductDet.Rows.Add(0, "", 0);
break;
case "DELETE":
dtProductDet.Rows.RemoveAt(Convert.ToInt32(e.CommandArgument));
break;
}
}
}
how can i achieve my aim.
The answer has already been given in previous comments. To spell it out...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
txtSODate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
//--
dtProductDet = new DataTable("dtProductDet");
dtProductDet.Columns.Add("PID", typeof(int));
dtProductDet.Columns.Add("PName", typeof(string));
dtProductDet.Columns.Add("Quan", typeof(decimal));
dtProductDet.Rows.Add(0,"",0);
//--
GridView1.DataSource = dtProductDet;
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName.ToUpper())
{
case "ADD":
dtProductDet.Rows.Add(0, "", 0);
break;
case "DELETE":
dtProductDet.Rows.RemoveAt(Convert.ToInt32(e.CommandArgument));
break;
}
GridView1.DataBind();
}
I have got the solution.
The problem is, when i am editing value in DropDownList or in TextBox, its value is not saving back to DataTable which is bind with GridView and TextBox and DropDownList.
There is no automatic way to do this, so we have to write manual code to save values back to DataTable.
When i asked the question add button was in GridViewColumn and it was command Column, now i have added a button in GridView Footer.
So when i click on "Add new row" button, page is posted back, at first page load event fires and then Button_Click event fires. I have add code on Page.Load event, if page is posted back then pick data from GridView and Save it to DataTable.
Nextly Button_click event fires, so a new row adds in DataTable and DataTable will assign in DataSource of GridView and DataBind method executes and re-generates GridView.
I have a DropDownList which is also bind to a different DataTable other than GridView, so that after DataBind() i have to select manually value in DropDownList as per saved in DataTable of GridView.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
txtSODate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
//--
dtProductDet = new DataTable("dtProductDet");
dtProductDet.Columns.Add("PID", typeof(int));
dtProductDet.Columns.Add("PName", typeof(string));
dtProductDet.Columns.Add("Quan", typeof(decimal));
dtProductDet.Rows.Add(0,"",0);
//--
SetGridViewSource();
}
else
{
DataTable dtPD = dtProductDet;
DropDownList ddlProd = null;
if (GridView1.Rows.Count > 0)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
ddlProd = (DropDownList)GridView1.Rows[i].Cells[gvci_Prod].FindControl("ddlProduct");
dtPD.Rows[i]["PID"] = Convert.ToInt32(ddlProd.SelectedItem.Value);
dtPD.Rows[i]["PName"] = ddlProd.SelectedItem.Text;
dtPD.Rows[i]["QUAN"] = ((TextBox)GridView1.Rows[i].Cells[gvci_Quan].FindControl("txtQuan")).Text;
}
}
dtProductDet = dtPD;
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
dtProductDet.Rows.Add(0, "", 0);
DataTable dtPDet = dtProductDet;
GridView1.DataSource = dtPDet;
GridView1.DataBind();
DropDownList ddlProd = null;
DataRow drFind = null;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
ddlProd = (DropDownList)GridView1.Rows[i].Cells[gvci_Prod].FindControl("ddlProduct");
drFind = dtProductMaster.Rows.Find(dtPDet.Rows[i]["PID"]);
if(drFind != null)
{
ddlProd.SelectedIndex = dtProductMaster.Rows.IndexOf(drFind);
}
}
}