JQGrid in asp.net not displaying data (not visible) - c#

I'm following this example and I'm having some hard time displaying data in a gridview. When the page is loaded it gets to GetData and returns values.
If in the immediate windows after I fill datatable and see the count ?dtResult.Rows.Count I get 1001. So I know I have data.
However, when the I debug the app I just get the three buttons. What am I missing here?
Here's the aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="TestApp.test" %>
<%# Register Assembly="Trirand.Web" TagPrefix="trirand" Namespace="Trirand.Web.UI.WebControls" %>
<!DOCTYPE html>
<html lang="en-us">
<head id="Head1" runat="server">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/redmond/jquery-ui.css" />
<!-- The jQuery UI theme extension jqGrid needs -->
<link rel="stylesheet" type="text/css" media="screen" href="/themes/ui.jqgrid.css" />
<!-- jQuery runtime minified -->
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-2.0.3.min.js" type="text/javascript"></script>
<!-- The localization file we need, English in this case -->
<script src="/js/trirand/i18n/grid.locale-en.js" type="text/javascript"></script>
<!-- The jqGrid client-side javascript -->
<script src="/js/trirand/jquery.jqGrid.min.js" type="text/javascript"></script>
<style type="text/css">
body, html { font-size: 80%; }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="message">
<script type="text/javascript">
function addRow() {
var grid = jQuery("#<%= JQGrid1.ClientID %>");
grid.editGridRow("new", grid.addDialogOptions);
}
function editRow() {
var grid = jQuery("#<%= JQGrid1.ClientID %>");
var rowKey = grid.getGridParam("selrow");
var editOptions = grid.getGridParam('editDialogOptions');
if (rowKey) {
grid.editGridRow(rowKey, editOptions);
}
else {
alert("No rows are selected");
}
}
function delRow() {
var grid = jQuery("#<%= JQGrid1.ClientID %>");
var rowKey = grid.getGridParam("selrow");
if (rowKey) {
grid.delGridRow(rowKey, grid.delDialogOptions);
}
else {
alert("No rows are selected");
}
}
</script>
<input type="button" onclick="addRow()" value="Add" />
<input type="button" onclick="editRow()" value="Edit" />
<input type="button" onclick="delRow()" value="Delete" />
<trirand:jqgrid runat="server" ID="JQGrid1"
OnRowDeleting="JQGrid1_RowDeleting"
OnRowAdding="JQGrid1_RowAdding"
OnRowEditing="JQGrid1_RowEditing">
<Columns>
<trirand:JQGridColumn DataField="Addressbookid" Editable="false" PrimaryKey="true" />
<trirand:JQGridColumn DataField="ClientName" Editable="true" />
<trirand:JQGridColumn DataField="Clientno" Editable="true" />
<trirand:JQGridColumn DataField="IndustryName" Editable="true" />
</Columns>
<ToolBarSettings ShowEditButton="true" ShowAddButton="true" ShowDeleteButton="true" />
<EditDialogSettings CloseAfterEditing="true" Caption="The Edit Dialog" />
<AddDialogSettings CloseAfterAdding="true" />
</trirand:jqgrid>
</div>
<br /><br />
</div>
</form>
Here's the codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace TestApp
{
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JQGrid1.DataSource = GetData();
JQGrid1.DataBind();
}
protected DataTable GetData()
{
if (Session["EditDialogData"] == null)
{
// Create a new Sql Connection and set connection string accordingly
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["Sandbox"].ConnectionString;
sqlConnection.Open();
string sqlStatement = "Select * from voiceportal.dbo.clients_v";
// Create a SqlDataAdapter to get the results as DataTable
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlStatement, sqlConnection);
// Create a new DataTable
DataTable dtResult = new DataTable();
// Fill the DataTable with the result of the SQL statement
sqlDataAdapter.Fill(dtResult);
Session["EditDialogData"] = dtResult;
return dtResult;
}
else
{
return Session["EditDialogData"] as DataTable;
}
}
}
}
Any suggestions on how I can fix this?
Thanks

My two cents.
Make sure that the grid locale js file is in the right place and served well to your browser. See the related line:
<script src="/js/trirand/i18n/grid.locale-en.js" type="text/javascript"></script>
Open up your developer console with F12, refresh the page and look for the downloaded files and error messages on the console which can tell if this doesn't go well.
Double check that the data you serve matches the column configuration. Pay special attention to camel casing. .NET properties start with uppercase, they are camel cased, but JSON data often starts with lowercase. That also depends on if you use any transformations (like NewtonSoft and stuff). I don't know what's in your voiceportal.dbo.clients_v table, please specify your schema. In your ASPX code Addressbookid and Clientno are not camel cased. Shouldn't they be AddressbookId and ClientNo? Depends on your schema and what actually comes through the wire.

Related

I have problems getting this javascript + asp.net to work

i have this little proyect that brings a little window to take the data from the "modal" window to the main but i have problems putting in to work.
The index:
%# Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebTest.Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript" src="Ventana.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HiddenField ID="valor1" runat="server" />
<asp:HiddenField ID="valor2" runat="server" />
<asp:TextBox ID="txtIdRutPersona" runat="server"></asp:TextBox>
<asp:Button ID="btnAbrirPopup" runat="server" Text="Abrir" />
</div>
</form>
</body>
</html>
the .cs part of index:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnAbrirPopup.Attributes.Add("onclick", "javascript:Asistencia('txtIdRutPersona');");
}
}
}
}
the "persona" window that is the page that bind the data to the index:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Persona.aspx.cs" Inherits="WebTest.Persona" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript" src="Ventana.js"></script>
<script type="text/javascript">
function cerrar()
{
self.close();
}
</script>
</head>
<body>
<form id="Buscar" method="post" runat="server">
<div>
<asp:TextBox ID="txtRut" runat="server"></asp:TextBox>
<asp:Button ID="btnOk" runat="server" Text="Aplicar" />
<asp:Button ID="btnCerrar" runat="server" Text="Cerrar" />
</div>
</form>
</body>
</html>
the .cs part of "persona":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest
{
public partial class Persona : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["form"] = Request.QueryString["formname"];
ViewState["txtRut"] = Request.QueryString["txtRut"];
ViewState["postBack"] = Request.QueryString["postBack"];
btnOk.Attributes.Add("onClick", $"window.opener.SetCodigo({ViewState["form"]},{ViewState["txtRut"]},{ViewState["postBack"]})");
btnCerrar.Attributes.Add("onClick", "cerrar()");
}
}
}
}
and the js:
var VentanaOrigen;
function Asistencia(txtRut) {
popUp = window.open('Persona.aspx?formname=' + document.forms[0].name + '&txtRut=' + txtRut, '', 'width=430,height=300,left=200,top=150,resizable=yes,status=yes,scrollbars=yes');
}
function SetCodigo(formulario, txtIdRutPersona, IdRutPersona, IPostback) {
eval('var theform = document.' + formulario + ';');
VentanaOrigen.close();
theform.elements[txtIdRutPersona].value = IdRutPersona;
if (IPostback)
__doPostBack(txtIdRutPersona, '');
}
sorry to bother with the large text but im kinda frustated right now, thanks!
It's difficult what you're trying to achieve. I am guessing:
index.aspx has a button to load a popup (which is not modal)
The button passes in the ID of textbox txtIdRutPersona
Index.aspx
<input type="button" value="Abrir" onclick="Asistencia('<%= txtIdRutPersona.ClientID %>')" />
Use client ID in case ASP.NET generates a different ID. Also you should get errors if you change ID (on a later date).
<script type="text/javascript">
function Asistencia(txtIdRutPersonaID) {
popUp = window.open('Persona.aspx?txtIdRutPersonaID=' + txtIdRutPersonaID, '', 'width=430,height=300,left=200,top=150,resizable=yes,status=yes,scrollbars=yes');
}
</script>
persona.aspx
<asp:TextBox ID="txtRut" runat="server"></asp:TextBox>
<input type="button" value="Aplicar" onclick="SetCodigo('<%= TxtIdRutPersonaID %>', '<%= txtRut.ClientID %>')" />
<input type="button" value="Cerrar" onclick="cerrar()" />
You can send the data to index.aspx using window.opener and the ID from index.aspx (txtIdRutPersonaID)
<script type="text/javascript">
function SetCodigo(txtIdRutPersonaID, txtRutID) {
if (window.opener != null && !window.opener.closed) {
var txtIdRutPersona = window.opener.document.getElementById(txtIdRutPersonaID);
// txtIdRutPersona is the textbox from index.aspx
txtIdRutPersona.value = document.getElementById(txtRutID).value;
}
window.close();
}
function cerrar()
{
self.close();
}
</script>
persona.aspx.cs
public string TxtIdRutPersonaID
{
get
{
return Request.QueryString["txtIdRutPersonaID"];
}
}
Alternatively you could use ASP.NET code behind to generate onclick event (but theres no good reason to). E.g:
btnOk.Attributes.Add("onclick", $"SetCodigo('{txtIdRutPersonaID}','{txtRut.ClientID}')");
Likewise, theres no reason to use ViewState["form"], ViewState["txtRut"] & ViewState["postBack"]

Update Text in ASP.NET text box

I'm trying to update text in an SQL database using a text box. This is for an admin to overwrite the data in the database. Having trouble declaring one of the variables.
The itemnametext doesn't exist in the current context.
Code for itemediting page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="admin_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>elmtree - Admin</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" />
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../styles/mylist.css" />
</head>
<body>
<form id="form1" runat="server">
<img src="images/ELleft.png" style="width:226px; height:52px; margin-top: 3px; margin-left: 17px; text-align: justify; float: none;"/></a></li>
<div class="container">
<h1> Item Edit </h1> </div>
<div class="container">
<div class="form-group">
<label class="col-sm-2 control-label">Item name: </label>
<div class="col-md-4">
<asp:TextBox ID="itemnameedit" runat="server" Text="" CssClass="form-control">
</asp:TextBox>
</div>
<div class="pull-right">
<asp:Button CssClass="btn btn-primary btn-lg" ID="updatebutton" role="button" runat="server" Text="save" OnClick="updatebutton_Click" />
</div>
</div>
</div>
</form>
</body>
</html>
Code for itemediting.aspx.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class admin_itemediting : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e)
{
int row = 0;
if (Request.QueryString["itemID"] != null){
row = int.Parse(Request.QueryString["itemID"]);
}
else{
Response.Redirect("itemedit.aspx");
}
string connectionString = WebConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
string query = "SELECT * FROM reports WHERE ID=#rowid";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#rowid", row);
SqlDataReader rdr = myCommand.ExecuteReader();
while (rdr.Read())
{
string myname = rdr["itemname"].ToString();
itemnametext.Text = myname;
}
}
protected void updatebutton_Click(object sender, EventArgs e){
string connectionString = WebConfigurationManager.ConnectionStrings ["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
string itemnametextupdate = itemnametext.Text;
string query = "UPDATE reports SET itemname = #itemnewname";
}
}
}
Your textbox name is itemnameedit so itemnametext is not found
<asp:TextBox ID="itemnametext" runat="server" Text="" CssClass="form-control"></asp:TextBox>
EDIT: Your aspx page is Default and you are posting code for itemediting.aspx.cs.Post the code for itemediting.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="admin_Default" %>
Just change ID of your texbox from itemnameedit to itemnametext
Update: change your reference here to match the codefile and codefile class. I dont think you have right reference, so codefile class admin_itemediting don't know any of your control in the aspx file.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="itemediting.aspx.cs" Inherits="admin_itemediting" %>

Passing date to a Crystal Report via a .NET page

I have a fully working Crystal Report that accepts a start and end parameter. These parameters are used in a SQL Command object in the report. I'm trying to embed the report into an ASP.NET webpage and pass the parameters from input boxes. Unfortunately the report loads with the parameters that were lasted used on the .rpt file and the input boxes do nothing (neither does the button). I was hoping that the report would not be visible until the parameters are set & the button is pressed.
As I am using <input type="date" /> I'm not 100% sure if it will work as I'm on .NET 4.0 & VS2010, which are both complaining about the input field (but allow the project to compile without any errors, just a warning). I have tried with text inputs though and had the same problem.
I have not found a lot of documentation that helps me with this so I may be missing something obvious. Please help!
See code below. Note that I am using the 'Classic H5BP' HTML5 boilerplate.
default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
public partial class _Default : System.Web.UI.Page
{
ReportDocument crystalReport = new ReportDocument();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CrystalReportViewer1.Visible = false;
}
else
{
CrystalReportViewer1.Visible = true;
BindReport();
}
}
private void Page_Init(object sender, EventArgs e)
{
ConfigureCrystalReports();
}
private void ConfigureCrystalReports()
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
crystalReport.Load(Server.MapPath("Report/Report1.rpt"));
crystalReport.Filename(Server.MapPath("Report/Report1.rpt"));
crystalReport.SetParameterValue("Start", text.Start);
crystalReport.SetParameterValue("End", date.End);
CrystalReportViewer1.DisplayGroupTree = false;
CrystalReportViewer1.HasCrystalLogo = false;
CrystalReportViewer1.HasPrintButton = false;
CrystalReportViewer1.HasExportButton = false;
CrystalReportViewer1.HasToggleGroupTreeButton = false;
CrystalReportViewer1.ReportSource = crystalReport;
}
}
default.aspx
<%# Page language="C#" %>
<%# Register Assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"
Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Report</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="stylesheet" href="css/normalize.min.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.8.3.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script> window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script type="text/javascript">
yepnope({
test: Modernizr.inputtypes.date,
nope: {
'css': '//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.4/css/jquery-ui.min.css',
'js': '//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js'
},
callback: { // executed once files are loaded
'js': function () { $('input[type=text]').('input[name=Start]').datepicker({ dateFormat: "yy-mm-dd" }); } // default HTML5 format
}
});
</script>
<div><b>Report</b></div>
<div align="center">
Enter Date from: <input type="text" id="Start" name="Start" />
Enter Date to: <input type="date" id="End" name="End" />
<input id="Submit" type="button" value="Refresh Report" onclick="btnSubmit_Click" /></div>
<div>
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"
AutoDataBind="True"
EnableDatabaseLogonPrompt="False"
EnableParameterPrompt="False"
GroupTreeImagesFolderUrl=""
Height="940px"
ReportSourceID="CrystalReportSource1"
ReuseParameterValuesOnRefresh="True"
ToolbarImagesFolderUrl=""
ToolPanelWidth="200px"
Width="1411px" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
<Report FileName="C:\Users\administrator.DEVELOPMENT\Documents\Visual Studio 2010\Web\Report\Report1.rpt">
</Report>
</CR:CrystalReportSource>
</div>
</form>
</body>
</html>
I fixed this by using report.SetParameterValue() and ensuring this was called upon the button submitting. I also made sure that the codebehind was referenced in my default.aspx - think this was stopping all of the code running.

General Errors with ASP.NET and C#

I am new to stackoverflow and am needing help.
Last night I was working on an ASP.NET webpage using C# [I'm all very new to it] and after losing a lot of my progress after a flash drive failure, I had to rewrite from a backup I stored on google drive. After putting it onto my computer, I received problems with one of my webpages. At first it did not recognize objects "existing in the current context" but I rewrote the page from hand, because I thought it was some trouble caused by copy-pasting things back. Now I get these errors:
Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends t he correct base class (e.g. Page or UserControl).
'ASP.index_aspx.GetTypeHashCode();: no suitable method found to override
'ASP.index_aspx.ProcessRequest(System.Web.HttpContext)': no suitable method found to override
'ASP.index_aspx' does not implement interface member 'System.Web.IHttpHandler.IsReusable'
I did not have these problems at all when working with the version that I lost. Here is my code:
This is my "upload.aspx" page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>BSHUpload</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/pure-min.css"/>
</head>
<body>
<!-- Menu -->
<div class="pure-menu pure-menu-open pure-menu-horizontal">
<ul>
<li>Home</li>
<li class="pure-menu-selected">Upload</li>
<li>Requests</li>
</ul>
</div>
<!-- Server-side Upload -->
<form id="form1" runat="server" style="padding-left: 2em">
<div>
<h1>Upload a File</h1>
</div>
<div>
<asp:Label ID="lblStatus1" runat="server" Text="---"></asp:Label>
<asp:FileUpload ID="fdFileDrop1" runat="server" />
<asp:Button ID="btnFileDrop1" runat="server" Text="upload" OnClick="btnFileDrop1_Click" />
</div>
</form>
</body>
</html>
And my code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnFileDrop1_Click(object sender, EventArgs e)
{
string strSavePath1 = "C:\\UploadBin\\";
if (fdFileDrop1.HasFile)
{
string strFileName = fdFileDrop1.FileName;
strSavePath1 += strFileName;
fdFileDrop1.SaveAs(strSavePath1);
lblStatus1.Text = "Your file was saved as " + strFileName;
}
else
{
lblStatus1.Text = "You did not specify a file to upload";
}
}
}
And because I think the bottom 3 errors are for the "index.aspx" page here is that also:
Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>BSHUpload</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/pure-min.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
</head>
<body style="height: 228px">
<!-- Menu -->
<div class="pure-menu pure-menu-open pure-menu-horizontal">
<ul>
<li>Home</li>
<li class="pure-menu-selected">Upload</li>
<li>Requests</li>
</ul>
</div>
<form id="form1" runat="server" style="padding-left: 2em">
</form>
<div>
<button id="button1">Testing</button>
<p id="toggle1">
Wala
</p>
<script>
$( "#button1" ).click(function() {
$( "#toggle1" ).slideToggle( "slow" );
})
</script>
</div>
</body>
</html>
Code Behind for index.aspx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class index: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
I really hope you guys can help because I'm stumped here. I'm pretty sure that both the inherits and the "System.Web.UI.Page" is correct but it says it is not.
The problem is on index.aspx. Check this at the very top of the file
CodeFile="upload.aspx.cs" Inherits="index"
That's wrong. You're pointing to the incorrect code file. It should be
CodeFile="index.aspx.cs" Inherits="index"

Generating asp controls with mark up in db [duplicate]

How do I generate the controls in a div based on the markup defined in a SQL Server database? Is it possible? If yes, then how? Can anyone give me resources?
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="lit" runat="server" ClientIDMode="Static" Mode="Transform"></asp:Literal>
</div>
</form>
</body>
</html>
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 WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection _newConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand storedProcedure = new SqlCommand("sp_getMarkup", _newConnection);
storedProcedure.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(storedProcedure);
_newConnection.Open();
da.Fill(ds);
_newConnection.Close();
DataTable dt = ds.Tables["Table"];
string s = (from str in dt.AsEnumerable()
where str.Field<int>("Id").Equals(1)
select str.Field<string>("elemMarkup")).SingleOrDefault().ToString();
this.lit.Text = s;
}
}
}
In the database I have stored string as
<asp:CheckBox ID="chk" runat="server" ClientIDMode="Static" />
Now the problem is the control is rendered on page but is not visible. I can see it in view source.
Can anyone help me?
You can use ParseControl which accepts a string and create controls on the fly.
The drawback is if server code is in the string, it will not be executed. In addition, you need to attach event manually such as button click events.
For example,
<script runat="server">
// This server code will not be executed
</script>
Here is another SO question using jquery ajax to load info from database
I would recommend having some type of sanitizing intermediary; otherwise you are opening yourself up to cross-site scripting (XSS) issues.
You could use a placeholder on a page like so:
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
And in your code behind, you could have several checks (all of which contain SQL statements querying the data in the database). The database could contain a field containing component names such as checkbox, button (various other controls). This saves you storing markup in the database fields..
Very rough representation of how the code would look like..
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// SQL Code here
// Datatable code here
// End of DataTable code
// Beginning of IF blocks
If (DataTable.Rows.Count > 0) {
If (your check != "checkbox") {
this.PlaceHolder1.Controls.Add(new Button(){
Text = "Added"}
}
}
// More if statements here
);
}
}
Alternatively if you insist on storing asp markup in the database, then you could just feed the asp markup into the placeholder using a loop (if there are more than one rows in your database)

Categories