I am trying to export gridview contents into Excel as given below, Excel is created but there is no content. but I am able to view the content in the webpage.
using System;
using System.IO;
using System.Reflection;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
using System.Web.UI;
using System.Web;
namespace CustomReports.Reports
{
public partial class Reports : System.Web.UI.Page
{
DataTable ResultTable = new DataTable();
GridView ResultGrid = new GridView();
protected void Page_Load(object sender, EventArgs e)
{
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void Button1_Click(object sender, EventArgs e)
{
DataColumn col1 = new DataColumn("S.No");
DataColumn col2 = new DataColumn("Workflow Name");
DataColumn col3 = new DataColumn("Subject Name");
DataColumn col4 = new DataColumn("Subject ID");
col1.DataType = System.Type.GetType("System.Int32");
col2.DataType = System.Type.GetType("System.String");
col3.DataType = System.Type.GetType("System.String");
col4.DataType = System.Type.GetType("System.String");
ResultTable.Columns.Add(col1);
ResultTable.Columns.Add(col2);
ResultTable.Columns.Add(col3);
ResultTable.Columns.Add(col4);
CoreServiceSession client = new CoreServiceSession();
SessionAwareCoreServiceClient csClient = client.GetClient();
var readoption = new ReadOptions();
ProcessesFilterData filter = new ProcessesFilterData()
{
BaseColumns = ListBaseColumns.IdAndTitle,
ProcessType = ProcessType.Historical
};
int i = 1;
foreach (IdentifiableObjectData data in csClient.GetSystemWideList(filter))
{
var processHistory = data as ProcessHistoryData;
if (processHistory != null)
{
DataRow row = ResultTable.NewRow();
row[col1] = i;
row[col2] = processHistory.Title;
foreach (var subjectdetails in processHistory.Subjects)
{
row[col3] = subjectdetails.Title.ToString();
row[col4] = subjectdetails.IdRef.ToString();
}
ResultTable.Rows.Add(row);
}
i++;
}
//GridView ResultGrid = new GridView();
ResultGrid.DataSource = ResultTable;
ResultGrid.DataBind();
Panel1.Controls.Add(ResultGrid);
}
protected void Button2_Click(object sender, EventArgs e)
{
ExporttoExcel(ResultGrid, "Reports");
}
protected void ExporttoExcel(GridView objGridView, string FileName)
{
string attachment = "attachment; filename=" + FileName + ".xls";
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/ms-excel";
StringWriter objStringWriter = new StringWriter();
HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
objGridView.RenderControl(objHtmlTextWriter);
HttpContext.Current.Response.Write(objStringWriter.ToString());
HttpContext.Current.Response.End();
}
}
}
Excel is not imporing the content from the gridview, its blank
ASPX Code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Reports.aspx.cs" Inherits="CustomReports.Reports.Reports" EnableEventValidation="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Custom Report Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="table1" runat="server">
<tr>
<td>
<asp:Label ID="CustomReports1" runat="server" Text="Custom Reports"
Font-Bold="True"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="SelectReportType2" runat="server" Text="Select Report Type"></asp:Label>
</td>
<td>
<asp:DropDownList ID="DDReportTypes" runat="server" Height="25px" Width="193px" onselectedindexchanged="DDReportTypes_SelectedIndexChanged" AutoPostBack = "true" ></asp:DropDownList>
</td>
</tr>
</table>
<table id="dynamictable" runat="server">
</table>
<table id="buttons">
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="Search" onclick="Button1_Click" />
</td>
<td>
<asp:Button ID="Button2" runat="server" Text="Export" onclick="Button2_Click" />
</td>
<td>
<asp:Button ID="Button3" runat="server" Text="GetValues" onclick="Button3_Click" />
</td>
</tr>
</table>
<asp:TextBox ID="TextBox0" runat="server" Height="28px" Width="355px"></asp:TextBox>
<asp:Panel ID="Panel1" runat="server">
<asp:GridView ID="ResultGrid" runat="server">
</asp:GridView>
</asp:Panel>
</div>
</form>
</body>
</html>
You don't need the form. Just render the grid:
ResultGrid.RenderControl(htw);
However, you need to add this code because usually the grid has to be in a form
public override void VerifyRenderingInServerForm(Control control)
{
}
Try export using this code...
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=fooreport.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
lstEarningReport.RenderControl(htmlWrite);
Response.Write("<table border='1' > ");
Response.Write(stringWrite.ToString());
Response.Write("</table>");
Response.End();
This is an old question but ran into it when I had the same problem. EnableViewState was set to false on the gridview in my case. Setting it back to true fixed the issue. I was also databinding the gridview before exporting it, also removed that.
Related
How to for loop asp:label or asp:PlaceHolder tag with select asp:checkbox any checkbox in .NET C# , because I can't for loop asp:label or asp:PlaceHolder tag with select asp:checkbox any checkbox in .NET C#.
My full source code.
https://github.com/doanga2007/CheckLoopQR
Sample code at the bottom.
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckLoopQR.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.6.4.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(window).load(function(){
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder><br /><br />
<p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
<asp:CheckBoxList
ID="CheckBox1"
runat="server"
Border="1"
BorderColor="LightGray"
Font-Size="Large"></asp:CheckBoxList>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing.Common;
using ZXing;
using ZXing.QrCode;
using System.Web.UI.WebControls;
namespace CheckLoopQR
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
long num = Convert.ToInt64(code);
int i;
for (i = 1; i < 11; i++)
{
num += i;
CheckBox1.Items.Add(new ListItem(" " + num));
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
if (CheckBox1.SelectedItem == null)
{
Response.Redirect("Default.aspx");
}
string code = CheckBox1.SelectedItem.Text;
CheckBox1.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
}
}
}
}
Good news : I have answer to How to for loop asp:label or asp:PlaceHolder tag with select asp:checkbox any checkbox in .NET C# (+ Bonus without declare Microsoft SQL Server database).
My full source code.
https://github.com/doanga2007/CheckLoopQR
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckLoopQR.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.6.4.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(window).load(function(){
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:CheckBox ID="checkAll" runat="server" Font-Size="Large"/><asp:Label id="checkTextAll" runat="server" Font-Size="Large"></asp:Label><br /><br />
<asp:CheckBoxList ID="CheckBox1" runat="server" Border="1"
BorderColor="LightGray" Font-Size="Large"></asp:CheckBoxList>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing.Common;
using ZXing;
using ZXing.QrCode;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace CheckLoopQR
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.checkTextAll.Text = " Check All";
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
long num = Convert.ToInt64(code);
int i;
for (i = 1; i < 4; i++)
{
num += i;
CheckBox1.Items.Add(new ListItem(" " + num));
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
if (CheckBox1.SelectedItem == null)
{
Response.Redirect("Default.aspx");
}
string[] texture = { "Selected Item Text1 : ", "Selected Item Text2 : ", "Selected Item Text3 : " };
int a = 0;
foreach (ListItem listItem in CheckBox1.Items)
{
if (listItem.Selected)
{
a++;
string code = listItem.Text;
CheckBox1.Visible = false;
checkAll.Visible = false;
checkTextAll.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
Label lblvalues = new Label();
lblvalues.Text += texture[a-1] + listItem.Text;
lblvalues.Font.Size = FontUnit.Large;
Label lblvalues2 = new Label();
lblvalues2.Text += texture[a-1] + listItem.Text;
lblvalues2.Font.Size = FontUnit.Large;
Label lblvalues3 = new Label();
lblvalues3.Text += texture[a-1] + listItem.Text;
lblvalues3.Font.Size = FontUnit.Large;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues2);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues3);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
}
}
else
{
//do something else
}
}
}
}
}
I have devloped the file uploading into document library in sharepoint 2013 using Managed client object model.
Here iS my upload.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication7.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td colspan="2" align="center">
<asp:Label Font-Bold="true" Text="Upload a documents to SharePoint 2013" runat="server" ID="lblSharePoint" />
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<asp:Label ID="lblLocalPath" runat="server" Text="Local Path:"></asp:Label>
</td>
<td>
<asp:FileUpload ID="FileLocalPath" Width="350" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblSharePointURL" runat="server" Text="SharePoint Site URL:"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtSharePointURL" Width="350" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblLibraryName" runat="server" Text="Library Name:"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtLibraryName" Width="350" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
and here is my upload.aspx.cs
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication7
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public ClientContext SPClientContext { get; set; }
public Web SPWeb { get; set; }
public string SPErrorMsg { get; set; }
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
string sURL = txtSharePointURL.Text;
string sDocName = string.Empty;
if (!string.IsNullOrWhiteSpace(sURL) && !string.IsNullOrWhiteSpace(txtLibraryName.Text) && (FileLocalPath.HasFile))
{
bool bbConnected = Connect(sURL, "abhishekr", "A123bhishek", "saras");
if (bbConnected)
{
Uri uri = new Uri(sURL);
string sSPSiteRelativeURL = uri.AbsolutePath;
sDocName = UploadFile(FileLocalPath.FileContent, FileLocalPath.FileName, sSPSiteRelativeURL, txtLibraryName.Text);
if (!string.IsNullOrWhiteSpace(sDocName))
{
lblMsg.Text = "The document " + sDocName + " has been uploaded successfully..";
lblMsg.ForeColor = Color.Blue;
}
else
{
lblMsg.Text = SPErrorMsg;
lblMsg.ForeColor = Color.Red;
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
}
public bool Connect(string SPURL, string SPUserName, string SPPassWord, string SPDomainName)
{
bool bConnected = false;
try
{
SPClientContext = new ClientContext(SPURL);
SPClientContext.Credentials = new NetworkCredential(SPUserName, SPPassWord, SPDomainName);
SPWeb = SPClientContext.Web;
SPClientContext.Load(SPWeb);
SPClientContext.ExecuteQuery();
bConnected = true;
}
catch (Exception ex)
{
bConnected = false;
SPErrorMsg = ex.Message;
Response.Write(ex.Message.ToString());
}
return bConnected;
}
public string UploadFile(Stream fs, string sFileName, string sSPSiteRelativeURL, string sLibraryName)
{
string sDocName = string.Empty;
try
{
if (SPWeb != null)
{
var sFileUrl = String.Format("{0}/{1}/{2}", sSPSiteRelativeURL, sLibraryName, sFileName);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(SPClientContext, sFileUrl, fs, true);
sDocName = sFileName;
}
}
catch (Exception ex)
{
sDocName = string.Empty;
SPErrorMsg = ex.Message;
Response.Write(ex.Message.ToString());
}
return sDocName;
}
}
}
it is working fine when i am uploading small files, it through an error when i uploading large file.
Error:" Maximum request length exceeded "
Please, help me how to resolve issue.
you can define max request length in SharePoint like this:
https://blogs.technet.microsoft.com/sammykailini/2013/11/06/how-to-increase-the-maximum-upload-size-in-sharepoint-2013/
In Central Admin>Application Management>Manage Web Applications> Select the desired web app and click General Settings on the ribbon
In web.config edit httpRuntime Node like this (for 2GB files and unlimited execution):
I looked for many solutions in google. I couldn't find out a solution. I have a grid view In my asp.net template this image
After submiting a file, i want to set submited file raw details to a new table in database. this is that table
(I am new for this subject)
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.IO;
public partial class Assignments : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Session["ID"].ToString();
DBL.AddAssignment obj12 = new DBL.AddAssignment();
SqlDataReader sqlDR12 = null;
sqlDR12 = obj12.Getbatchofstudent(Session["ID"].ToString().Trim());
while(sqlDR12.Read())
{
Label1.Text=sqlDR12[9].ToString().Trim();
}
String BID = Label1.Text;
DBL.AddAssignment obj = new DBL.AddAssignment();
SqlDataReader sqlDR = null;
sqlDR = obj.Viewassignmentingrid(BID);
if (!IsPostBack)
{
grid1.DataSource = sqlDR;
grid1.DataBind();
}
}
protected void grid1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void grid1_Disposed(object sender, EventArgs e)
{
}
protected void grid1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Button bts = e.CommandSource as Button;
Response.Write(bts.Parent.Parent.GetType().ToString());
if (e.CommandName.ToLower() != "upload")
{
return;
}
FileUpload fu = bts.FindControl("FileUpload4") as FileUpload;//here
if (fu.HasFile)
{
bool upload = true;
string fleUpload = Path.GetExtension(fu.FileName.ToString());
if (fleUpload.Trim().ToLower() == ".xls" | fleUpload.Trim().ToLower() == ".xlsx")
{
fu.SaveAs(Server.MapPath("~/UpLoadPath/" + fu.FileName.ToString()));
string uploadedFile = (Server.MapPath("~/UpLoadPath/" + fu.FileName.ToString()));
//Someting to do?...
}
else
{
upload = false;
Response.Write("<script type=\"text/javascript\">alert('Sorry, Your file didn't uploaded to the server. Try again. Make sure that your are uploading .Docx or .Doc files');</script>");
// Something to do?...
}
if (upload)
{
Response.Write("<script type=\"text/javascript\">alert('Your file has been successfully uploaded to the server. Thank you');</script>");
}
}
}
protected void grid1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//int index = e.RowIndex;
//GridViewRow row = (GridViewRow)grid1.Rows[index];
//Label AssignmentID = (Label)row.FindControl("LblASGNID");
//Label AssignmentName = (Label)row.FindControl("LblCASGNName");
//Label Coursename = (Label)row.FindControl("LblCourseName");
//Label BatchID = (Label)row.FindControl("LabelBatch");
//Label SubjectID = (Label)row.FindControl("LblSubID");
//Label Subjectname = (Label)row.FindControl("LblSubname");
//Label Submissiondate = (Label)row.FindControl("LblSubdate");
//DateTime Submiteddate= DateTime.Now;
//FileUpload fu = (FileUpload)row.FindControl("fu1");
//if (fu.HasFile)
//{
// DBL.AddAssignment obj12 = new DBL.AddAssignment();
// SqlDataReader sqlDR12 = null;
// sqlDR12 = obj12.Getbatchofstudent(Session["ID"].ToString().Trim());
// while (sqlDR12.Read())
// {
// Session["ID2"] = sqlDR12[0].ToString().Trim();
// }
// //string file = System.IO.Path.Combine(Server.MapPath("~/UpLoadPath/"), fu.FileName);
// //fu.SaveAs(file);
// {
// DBL.Assignmentuploadeddetails obj = new DBL.Assignmentuploadeddetails();
// obj.SID1 = Session["ID2"].ToString().Trim();
// obj.AssignmentID1 = AssignmentID.ToString().Trim();
// obj.Assignmentname1 = AssignmentName.ToString().Trim();
// obj.Coursename1 = Coursename.ToString().Trim();
// obj.BatchID = BatchID.ToString().Trim();
// obj.SubjectID1 = SubjectID.ToString().Trim();
// obj.SubjectName1 = Subjectname.ToString().Trim();
// obj.SubmissionDate1 = DateTime.Parse(Submissiondate.ToString());
// obj.SubmitedDate1 = Submiteddate;
// obj.UploadAssignment(obj);
// }
//}
//SqlCommand cmd1 = new SqlCommand("update Employee set EmpName='" + ename.Text + "',EmpEmailId='" + emid.Text + "',EmpMobileNum=" + Convert.ToInt64(mnumber.Text) + "", con);
//con.Open();
//int res1 = cmd1.ExecuteNonQuery();
//con.Close();
//if (res1 == 1)
//{
// Response.Write("<script>alert('Updation done!')</script>");
//}
//gv1.EditIndex = -1;
//Bind();
}
}
**This is ASP.NET cooding**
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Assignment Upload.aspx.cs" Inherits="Assignments" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8"/>
<!-- Set the viewport width to device width for mobile -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="description" content=""/>
<title>Student Profile</title>
<!-- ============ Google fonts ============ -->
<link href='http://fonts.googleapis.com/css?family=EB+Garamond' rel='stylesheet'
type='text/css' />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,600,700,300,800'
rel='stylesheet' type='text/css' />
<!-- ============ CSS here ============ -->
<link href="css/1bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="css/style1.css" rel="stylesheet" type="text/css" />
<link href="css/1font-awesome.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div id="custom-bootstrap-menu" class="navbar navbar-default " role="navigation">
<div class="container">
<div class="navbar-header">
<table>
<tr>
<td><img src="images/logonuwana.png" style="background-color:transparent" width="60" height="60"/></td>
<td><a class="navbar-brand" href="#" style="font-size:medium" >Nuwana School Student Information System</a></td>
</tr>
</table>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-menubuilder">
<span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span
class="icon-bar"></span><span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse navbar-menubuilder">
<ul class="nav navbar-nav navbar-right">
<li>Home </li>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12" style="width:1000px">
<div class="registrationform">
<div class="form-horizontal">
<fieldset>
<legend>Student Profile <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<%--2016.01.18--%>
<asp:Label ID="Label1" runat="server" Text="" CssClass="col-lg-2 control-label"></asp:Label>
<div class="col-lg-10" style="width:600px">
<asp:Label ID="StudentNo" runat="server" Text="" CssClass="form-control" Font-Names="AmericanTypewriter-Light" ForeColor="#66FF66" Font-Bold="True" Font-Size="12"></asp:Label>
</div>
</div>
<div class="form-group">
<asp:GridView ID="grid1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="Both" AllowPaging="False" AlternatingRowStyle-Wrap="True" AutoGenerateSelectButton="False" EditIndex="-1" SelectedIndex="-1" UseAccessibleHeader="True" OnDisposed="grid1_Disposed" OnRowCommand="grid1_RowCommand" OnRowUpdating="grid1_RowUpdating" OnSelectedIndexChanged="grid1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<columns>
<asp:TemplateField HeaderText="Assignment Name">
<ItemTemplate>
<asp:Label ID="LblCASGNName" runat="server" Text='<%#Bind("Assignmetname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assignment ID">
<ItemTemplate>
<asp:Label ID="LblASGNID" runat="server" Text='<%#Bind("AssignmentID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Course Name">
<ItemTemplate>
<asp:Label ID="LblCourseName" runat="server" Text='<%#Bind("CourseName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Batch">
<ItemTemplate>
<asp:Label ID="LabelBatch" runat="server" Text='<%#Bind("BatchID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject Name">
<ItemTemplate>
<asp:Label ID="LblSubname" runat="server" Text='<%#Bind("SubjectName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject ID">
<ItemTemplate>
<asp:Label ID="LblSubID" runat="server" Text='<%#Bind("SubjectID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Issued Date">
<ItemTemplate>
<asp:Label ID="LblIssueddate" runat="server" Text='<%#Bind("Issueddate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Submission Date">
<ItemTemplate>
<asp:Label ID="LblSubdate" runat="server" Text='<%#Bind("Submissiondate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Logo Upload">
<ItemTemplate>
<asp:FileUpload ID="FileUpload4" runat="server" /><asp:Button ID="bt_upload" runat="server" EnableViewState="False" Text="Upload" CommandName="Upload" Height="22" Width="120" />
</ItemTemplate>
</asp:TemplateField>
</columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</div>
<%-- <div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<asp:Button ID="btnSubmit" runat="server" CssClass="btn btn-primary" Text="Next" OnClick="btnSubmit_Click" />
<asp:Button ID="btnCancel" runat="server" CssClass="btn btn-warning" Text="Cancel" OnClick="btnCancel_Click" />
</div>
</div>--%>
</fieldset>
</div>
</div>
</div>
</div>
<script src="js/1jquery.js" type="text/javascript"></script>
<script src="js/1bootstrap.min.js" type="text/javascript"></script>
<script src="js/jquery.backstretch.js" type="text/javascript"></script>
<script type="text/javascript">
'use strict';
$.backstretch(
[
"images/44.jpg",
],
{
duration: 4500,
fade: 1500
}
);
</script>
</form>
</body>
</html>
Thank you so much for your help Piyush Khatri. I found out a way to do it. Here it is.
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.IO;
public partial class Assignments : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Session["ID"].ToString();
DBL.AddAssignment obj12 = new DBL.AddAssignment();
SqlDataReader sqlDR12 = null;
sqlDR12 = obj12.Getbatchofstudent(Session["ID"].ToString().Trim());
while(sqlDR12.Read())
{
Label1.Text=sqlDR12[9].ToString().Trim();
}
String BID = Label1.Text;
DBL.AddAssignment obj = new DBL.AddAssignment();
SqlDataReader sqlDR = null;
sqlDR = obj.Viewassignmentingrid(BID);
if (!IsPostBack)
{
grid1.DataSource = sqlDR;
grid1.DataBind();
}
}
protected void grid1_Disposed(object sender, EventArgs e)
{
}
protected void grid1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Button bts = e.CommandSource as Button;
Response.Write(bts.Parent.Parent.GetType().ToString());
if (e.CommandName.ToLower() != "upload")
{
return;
}
FileUpload fu = bts.FindControl("FileUpload4") as FileUpload;//here
if (fu.HasFile)
{
bool upload = true;
string fleUpload = Path.GetExtension(fu.FileName.ToString());
if (fleUpload.Trim().ToLower() == ".xls" | fleUpload.Trim().ToLower() == ".xlsx")
{
//Someting to do?...
GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int rowIndex = gvr.RowIndex;
GridViewRow row = (GridViewRow)grid1.Rows[rowIndex];
Label AssignmentID = (Label)row.FindControl("LblASGNID");
Label AssignmentName = (Label)row.FindControl("LblCASGNName");
Label Coursename = (Label)row.FindControl("LblCourseName");
Label BatchID = (Label)row.FindControl("LabelBatch");
Label SubjectID = (Label)row.FindControl("LblSubID");
Label Subjectname = (Label)row.FindControl("LblSubname");
Label Submissiondate = (Label)row.FindControl("LblSubdate");
DateTime Submiteddate = DateTime.Now;
FileUpload fu1 = (FileUpload)row.FindControl("FileUpload4");
if (fu1.HasFile)
{
DBL.Assignmentuploadeddetails objf = new DBL.Assignmentuploadeddetails();
SqlDataReader sqlDRf = null;
sqlDRf = objf.GetcourseID(Session["ID"].ToString().Trim(), AssignmentID.Text.ToString());
if (sqlDRf.Read())
{
Response.Write("<script type=\"text/javascript\">alert('Your assignment For this subject has been already submited');</script>");
upload = false;
}
else if (Convert.ToDateTime(Submissiondate.Text.ToString()) < DateTime.Now)
{
Response.Write("<script type=\"text/javascript\">alert('Sorry Your Submission Date is Over');</script>");
upload = false;
}
else
{
DBL.AddAssignment obj12 = new DBL.AddAssignment();
SqlDataReader sqlDR12 = null;
sqlDR12 = obj12.Getbatchofstudent(Session["ID"].ToString().Trim());
while (sqlDR12.Read())
{
Session["ID2"] = sqlDR12[0].ToString().Trim();
}
DBL.Assignmentuploadeddetails obj = new DBL.Assignmentuploadeddetails();
obj.SID1 = Session["ID2"].ToString().Trim();
obj.AssignmentID1 = AssignmentID.Text;
obj.Assignmentname1 = AssignmentName.Text;
obj.Coursename1 = Coursename.Text;
obj.BatchID = BatchID.Text;
obj.SubjectID1 = SubjectID.Text;
obj.SubjectName1 = Subjectname.Text;
obj.SubmissionDate1 = Convert.ToDateTime(Submissiondate.Text.ToString());
obj.SubmitedDate1 = Submiteddate;
obj.UploadAssignment(obj);
fu.SaveAs(Server.MapPath("~/UpLoadPath/" + fu.FileName.ToString()));
string uploadedFile = (Server.MapPath("~/UpLoadPath/" + fu.FileName.ToString()));
}
}
}
else
{
upload = false;
Response.Write("<script type=\"text/javascript\">alert('Sorry, Your file didn't uploaded to the server. Try again. Make sure that your are uploading .Docx or .Doc files');</script>");
// Something to do?...
}
if (upload)
{
Response.Write("<script type=\"text/javascript\">alert('Your file has been successfully uploaded to the server. Thank you');</script>");
}
}
}
protected void bt_upload_Click(object sender, EventArgs e)
{
}
protected void grid1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
}
So on a textbox I will write how many dropdownlists, textboxes, label etc and the page ia AutoPostBack. But after I choose an item on a gridview, the page ia autopostback and all the data dissapear. I want gridview to be AutoPostBack but how can I make it not to dissapear all the other item I have added from the first textbox?
For more info here is the source code:
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 248px;
}
.auto-style2 {
width: 253px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<table style="width:100%;">
<tr>
<td class="auto-style2">
</td>
<td>
</td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder3" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder4" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder5" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
</td>
<td> </td>
</tr>
</table>
<br />
</div>
</form>
</body>
</html>
and 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 System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
DropDownList artikulli;
TextBox cmimi;
Label tregoCmimi;
TextBox sasia;
Label cmimiGjithsej;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox1.Text))
{
int a = int.Parse(TextBox1.Text);
for (int j = 1; j <= a; j++)
{
Guid IDUnik = new Guid();
artikulli = new DropDownList();
cmimi = new TextBox();
tregoCmimi = new Label();
sasia = new TextBox();
cmimiGjithsej = new Label();
artikulli.ID = j.ToString(IDUnik.ToString("N").Substring(31));
artikulli.AutoPostBack = true;
cmimi.ID = j.ToString(IDUnik.ToString("D").Substring(30));
tregoCmimi.ID = j.ToString(IDUnik.ToString("P"));
sasia.ID = j.ToString(j.ToString(IDUnik.ToString("X")));
cmimiGjithsej.ID = j.ToString(j.ToString(IDUnik.ToString("B"))); ;
PlaceHolder1.Controls.Add(artikulli);
PlaceHolder2.Controls.Add(cmimi);
PlaceHolder3.Controls.Add(tregoCmimi);
PlaceHolder4.Controls.Add(sasia);
PlaceHolder5.Controls.Add(cmimiGjithsej);
artikulli.Items.Insert(0, new ListItem("<Select Subject>", "0"));
artikulli.Items.Insert(1, new ListItem("<Select Subject>", "1"));
}
}
}
}
you can do as below
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
AddItems();
}
}
private void AddItems()
{
if (!string.IsNullOrEmpty(TextBox1.Text))
{
int a = int.Parse(TextBox1.Text);
for (int j = 1; j <= a; j++)
{
Guid IDUnik = new Guid();
artikulli = new DropDownList();
cmimi = new TextBox();
tregoCmimi = new Label();
sasia = new TextBox();
cmimiGjithsej = new Label();
artikulli.ID = j.ToString(IDUnik.ToString("N").Substring(31));
artikulli.AutoPostBack = true;
cmimi.ID = j.ToString(IDUnik.ToString("D").Substring(30));
tregoCmimi.ID = j.ToString(IDUnik.ToString("P"));
sasia.ID = j.ToString(j.ToString(IDUnik.ToString("X")));
cmimiGjithsej.ID = j.ToString(j.ToString(IDUnik.ToString("B"))); ;
PlaceHolder1.Controls.Add(artikulli);
PlaceHolder2.Controls.Add(cmimi);
PlaceHolder3.Controls.Add(tregoCmimi);
PlaceHolder4.Controls.Add(sasia);
PlaceHolder5.Controls.Add(cmimiGjithsej);
artikulli.Items.Insert(0, new ListItem("<Select Subject>", "0"));
artikulli.Items.Insert(1, new ListItem("<Select Subject>", "1"));
}
}
}
you don't need OnTextChanged="TextBox1_TextChanged" in your textbox
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Populate();
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Populate();
}
void Populate()
{
PlaceHolder1.Controls.Clear();
PlaceHolder2.Controls.Clear();
PlaceHolder3.Controls.Clear();
PlaceHolder4.Controls.Clear();
PlaceHolder5.Controls.Clear();
if (!string.IsNullOrEmpty(TextBox1.Text))
{
int a = int.Parse(TextBox1.Text);
for (int j = 1; j <= a; j++)
{
Guid IDUnik = new Guid();
artikulli = new DropDownList();
cmimi = new TextBox();
tregoCmimi = new Label();
sasia = new TextBox();
cmimiGjithsej = new Label();
artikulli.ID = j.ToString(IDUnik.ToString("N").Substring(31));
artikulli.AutoPostBack = true;
cmimi.ID = j.ToString(IDUnik.ToString("D").Substring(30));
tregoCmimi.ID = j.ToString(IDUnik.ToString("P"));
sasia.ID = j.ToString(j.ToString(IDUnik.ToString("X")));
cmimiGjithsej.ID = j.ToString(j.ToString(IDUnik.ToString("B"))); ;
PlaceHolder1.Controls.Add(artikulli);
PlaceHolder2.Controls.Add(cmimi);
PlaceHolder3.Controls.Add(tregoCmimi);
PlaceHolder4.Controls.Add(sasia);
PlaceHolder5.Controls.Add(cmimiGjithsej);
artikulli.Items.Insert(0, new ListItem("<Select Subject>", "0"));
artikulli.Items.Insert(1, new ListItem("<Select Subject>", "1"));
}
}
}
I have table with 20 to 30 rows and 3 columns. I would like to add fourth column with buttons or something in the cell that I can click on it. And onClick event I need to get info in which row has happened this click.
Table is generated programmatically on the fly.
Can this be done and I beg for some examples.
EDIT 2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HelpdeskOsControl
{
public partial class Test : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
//GenerateTable(getTestData());
}
private List<string> getTestData()
{
List<string> tData = new List<string>();
for (int i = 0; i < 10; i++)
{
tData.Add("proc" + i + "_" + new Random().Next(100) + "_" + new Random().Next(100));
}
return tData;
}
protected void btnClear_Click(object sender, EventArgs e)
{
for (int i = Processes.Rows.Count; i > 1; i--)
{
Processes.Rows.RemoveAt(i - 1);
}
}
protected void btnLoad_Click(object sender, EventArgs e)
{
GenerateTable(getTestData());
}
protected void btnKill_Click(object sender, EventArgs e)
{
lblView.Text = ((Button)sender).ID;
}
private void GenerateTable(List<string> list)
{
int st = 0;
foreach (string line in list)
{
TableRow tr = new TableRow();
Processes.Controls.Add(tr);
foreach(String str in line.Split('_'))
{
int index = tr.Cells.Add(new TableCell());
tr.Cells[index].Text = str;
}
Button b = new Button();
b.Text = "Kill " + st;
b.ID = "btnKill_" + st;
b.Click += new EventHandler(btnKill_Click);
TableCell tc = new TableCell();
tc.Controls.Add(b);
tr.Cells.Add(tc);
tr.TableSection = TableRowSection.TableBody;
Processes.Rows.Add(tr);
st++;
}
Processes.BorderStyle = BorderStyle.Solid;
Processes.GridLines = GridLines.Both;
Processes.BorderWidth = 2;
}
}
}
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Test.ascx.cs" Inherits="HelpdeskOsControl.Test" %>
<asp:Panel ID="Panel1" runat="server" Height="465px" Width="417px">
<asp:Table ID="Processes" runat="server" Height="20px" Width="400px" CssClass="tablesorter">
<asp:TableHeaderRow ID="ProcessesHeader" runat="server"
TableSection="TableHeader">
<asp:TableHeaderCell ID="TableHeaderCell1" runat="server">Name</asp:TableHeaderCell>
<asp:TableHeaderCell ID="TableHeaderCell2" runat="server">CPU</asp:TableHeaderCell>
<asp:TableHeaderCell ID="TableHeaderCell3" runat="server">Memory</asp:TableHeaderCell>
<asp:TableHeaderCell ID="TableHeaderCell4" runat="server"></asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
<asp:Panel ID="Panel2" runat="server">
<asp:Button ID="btnLoad" runat="server" onclick="btnLoad_Click" Text="Load" />
<asp:Button ID="btnClear" runat="server" onclick="btnClear_Click"
Text="Clear" />
<asp:Label ID="lblView" runat="server" Text="Label"></asp:Label>
</asp:Panel>
</asp:Panel>
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="HelpdeskOsControl._Default" %>
<%# Register src="Test.ascx" tagname="WebUserControl" tagprefix="Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>Test Control</p>
<Test:WebUserControl ID="Test" runat="server" />
</div>
</form>
</body>
</html>
Can please someone checks why this code is NOT working when I comment out GenerateTable(getTestData()); in Page_Load procedure.
If it is a HTMLtable generated in code behind,
assuming this is how your code looks like,
HtmlButton b = new HtmlButton();
b.ClientID = "Button_" + i;
b.Attributes.Add("onClick", "your function(this)");
use the suffix part from the parameter in the method to check which butto has been click.
Hope this helps!!
Edit:
You may still go with the above logic. In the click event of the button ( which appears to be common for all the buttons), you ca use the sender object and get the ID and know which button has been clicked as follows:
protected void KillButton_Click(object sender, EventArgs e)
{
string ID = ((Button)sender).ID;
}
and you may attach the event handler in this fashion:
b.Click += new EventHandler(KillButton_Click);
ClientID is read Only...therefore you cannot have the line that tries to set the clientID