Binding ASP.NET listview to DataTable variable - asp.net

I am binding a listview to datatable variable. My idea is to modify the DataTable upon Delete, Insert, Update Requests from ListView, and save it to Database only when user wants. But, after postback, my DataTable becomes null. Is there any way to resolve it? Is this right way to bind a ListView without connecting Database ?
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){
DataTable DTReceipts = new DataTable("DTReceipts");
DTReceipts.Columns.AddRange(new DataColumn[] {
new DataColumn("ExpenseReceiptID", Type.GetType("System.Int32")),
new DataColumn("TransactionSeqNumber", Type.GetType("System.Int32")),
new DataColumn("TransactionSeqSub", Type.GetType("System.String")),
new DataColumn("TransactionDate", Type.GetType("System.DateTime")),
new DataColumn("ReceiptNumber", Type.GetType("System.String")),
new DataColumn("Vendor_EntityID", Type.GetType("System.Int32")),
new DataColumn("Description", Type.GetType("System.String")),
new DataColumn("SubProjectID", Type.GetType("System.Int32")),
new DataColumn("AllocationID", Type.GetType("System.Int32")),
new DataColumn("AllocationScope", Type.GetType("System.String")),
new DataColumn("DeductFromVendor_EntityID", Type.GetType("System.Int32")),
new DataColumn("DeductionAmount", Type.GetType("System.Double")),
new DataColumn("EmployeeID", Type.GetType("System.Int32"))
});
for (int i = 1; i <= 20; i++)
{
DataRow drr = DTReceipts.NewRow();
drr["ExpenseReceiptID"] = DBNull.Value;
drr["TransactionSeqNumber"] = i.ToString();
drr["TransactionSeqSub"] = "";
drr["TransactionDate"] = DBNull.Value;
drr["ReceiptNumber"] = DBNull.Value;
drr["Vendor_EntityID"] = DBNull.Value;
drr["Description"] = DBNull.Value;
drr["SubProjectID"] = DBNull.Value;
drr["AllocationID"] = DBNull.Value;
drr["AllocationScope"] = DBNull.Value;
drr["DeductFromVendor_EntityID"] = DBNull.Value;
drr["DeductionAmount"] = DBNull.Value;
drr["EmployeeID"] = DBNull.Value;
DTReceipts.Rows.Add(drr);
}
ExpenseReceiptsList.DataSource = DTReceipts;
ExpenseReceiptsList.DataBind();
}
}

Related

Dynamically adding Table rows

I am trying to add values in table rows on button click. It's working on database but not working on web page. It override on last row on page.
How can I generate new row on every button click.
here is my button click code--
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//Label2.Visible = false;
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
CheckBox cb1 = new CheckBox();
I = Hidden1.Value;
I += 1;
cb1.ID = "cb1" + I;
TableRow Table1Row = new TableRow();
Table1Row.ID = "Table1Row" + I;
TableCell RCell1 = new TableCell();
RCell1.Controls.Add(cb1);
TableCell RCell2 = new TableCell();
RCell2.Text = txtName.Text;
tblLanguagesRow.Cells.Add(RCell1);
tblLanguagesRow.Cells.Add(RCell2);
tblLanguages.Rows.Add(tblLanguagesRow);
Hidden1.Value = I;
btnAdd.Visible = true;
btnDelete.Visible = true;
Label2.Visible = true;
Label2.Text = "Successfully Added";
add();
}
txtName.Text = "";
}
public int add()
{
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("hrm_AddLanguages", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtName.Text;
command.Parameters.Add("#CreatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#UpdatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#CreatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#UpdatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#IsDeleted", SqlDbType.Bit).Value = 0;
sqlConnection.Open();
return command.ExecuteNonQuery();
}
Please Help me.
If possible try to do this using Grid view. It is better to use grid view instead of table.
Check out below link. It will help you to find your solution.
DataTable in ASP.Net Session

how to return a datatable if a register number exists

I am trying to display a grid if the user entered register number exists in database, if the register number does not exists this means that I need to display one label also.i am a new one in asp.net,so please help me.
Here is my code below.
public DataTable madhrasaViewByRegNo(string viewByNo)
{
try
{
madhrasaInfo infomadhrasa = new madhrasaInfo();
object decobj = new object();
if (sqlcon.State == ConnectionState.Closed)
{
sqlcon.Open();
}
SqlCommand sqlcmd = new SqlCommand("madhrasaViewByRegNo", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.Add("#regNo", SqlDbType.VarChar).Value = viewByNo;
decobj = sqlcmd.ExecuteNonQuery();
if (decobj == null)
{
decStuId = decimal.Parse(decobj.ToString());
}
else
{
DataTable dtbClass = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter("madhrasaViewByRegNo", sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.SelectCommand.Parameters.Add("#regNo", SqlDbType.VarChar).Value = viewByNo;
sqlda.Fill(dtbClass);
return dtbClass;
}
}
catch (Exception)
{
throw;
}
return null;
}
public void gridfillByNo()
{
madhrasaSp spMadhrasa = new madhrasaSp();
DataTable dtbl = new DataTable();
dtbl = spMadhrasa.madhrasaViewByRegNo(TextBox2.Text);
gvstuResult.DataSource = dtbl;
gvstuResult.DataBind();
}
public void regSearch()
{
madhrasaSp spmadhrasa = new madhrasaSp();
spmadhrasa.madhrasaViewByRegNo(TextBox2.Text);
if (madhrasaSp.decStuId > 0)
{
gridfillByNo();
MultiView1.ActiveViewIndex = 1;
}
else
{
MultiView1.ActiveViewIndex = 0;
Label1.Visible = true;
Label1.Text = "Invalid Register Number";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
regSearch();
}
You Dont you just set the grid view's EmptyDataText to 'Reg No Dosent exist'. It will solve your ploblem.
<asp:GridView ID="GridView1" runat="server" EmptyDataText="register number not available">
</asp:GridView>

Dynamic Checkbox event handler asp.net

I found a few questions related to this, but none that I could figure out how to apply to my issue. Anyway, I have a ASP webform that pulls questions and answers from a database and puts them in a table. In the table, I have a column with a checkbox where the user can flag questions. My problem is that event handler for the CheckChanged event is not firing. I read some things about postback and whatnot, but my issue is that these controls are not created until the retrieve question button is pressed. Any help or pointers would be great.
Thanks,
Joseph
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ScienceAssessmentToolASP
{
public partial class createnewtest : System.Web.UI.Page
{
private int n;
private SqlConnection conn = null;
private List<int> flaggedQuestions = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
GetConn();
ExecuteRetrieval();
n = 1;
}
catch (Exception ex) { n = 0; Response.Write("for debugging: " + ex); }
finally { if (conn != null) conn.Close(); }
if (n < 0)
//Label1.Text = "Connection Successful";
Label3.Text = "Failed to Connect to Database, please contact the administrator.";
}
private void GetConn()
{
string connString = #"
removed ";
conn = new SqlConnection(connString);
conn.Open();
}
private void ExecuteRetrieval()
{
List<string> names = new List<string>(),
types = new List<string>();
SqlDataReader reader = null;
string query = "select * from [ScienceQA] where [GradeLevel] = " + DropDownList1.Text +
" and [Topic] = '" + DropDownList2.Text + "';";
SqlCommand cmd = new SqlCommand(query, conn);
reader = cmd.ExecuteReader();
TableHeaderRow headerRow = new TableHeaderRow();
TableHeaderCell idH = new TableHeaderCell();
TableHeaderCell questionH = new TableHeaderCell();
TableHeaderCell answerH = new TableHeaderCell();
TableHeaderCell flagH = new TableHeaderCell();
idH.Text = "ID";
questionH.Text = "Question";
answerH.Text = "Answer";
flagH.Text = "Flag";
headerRow.Cells.Add(idH);
headerRow.Cells.Add(questionH);
headerRow.Cells.Add(answerH);
headerRow.Cells.Add(flagH);
resultTable.Controls.Add(headerRow);
while (reader.Read())
{
TableRow row = new TableRow();
TableCell idCell = new TableCell();
TableCell qCell = new TableCell();
TableCell aCell = new TableCell();
TableCell flag = new TableCell();
idCell.Text = reader[0].ToString();
qCell.Text = reader[1].ToString();
aCell.Text = reader[2].ToString();
CheckBox flagBox = new CheckBox();
flagBox.ID = "flag" + idCell.Text.ToString();
//flagBox.Text = "Flag";
flagBox.CheckedChanged += new System.EventHandler(flagButton_Click);
flag.Controls.Add(flagBox);
row.Cells.Add(idCell);
row.Cells.Add(qCell);
row.Cells.Add(aCell);
row.Cells.Add(flag);
resultTable.Controls.Add(row);
}
Label4.Visible = true;
flagCounter.Visible = true;
resultTable.Visible = true;
}
protected void flagButton_Click(object sender, EventArgs e)
{
CheckBox lb = (CheckBox)sender;
int questionID = Convert.ToInt32(lb.Text.Substring(4));
if (lb.Checked)
{
lb.Checked = false;
flaggedQuestions.Add(questionID);
flagCounter.Text = Convert.ToString(Convert.ToInt32(flagCounter.Text) - 1);
}
else
{
lb.Checked = true;
flaggedQuestions.Remove(questionID);
flagCounter.Text = Convert.ToString(Convert.ToInt32(flagCounter.Text) + 1);
}
}
}
}
Try setting AutoPostBack to true when you create the control:
flagBox.AutoPostBack = true;
This makes it so the event will cause a postback. If you don't have this the code won't fire until you submit the form.
I figured it out. I guess I didnt need anything in button handler, since the clicking of the button causing a postback. So I put all the button1 handler stuff in my pageload with a if(postback) check and that worked.

How to populate the date present in the database table to Calender asp.net?

My table in the database has the following columns id , eventstart , eventend , eventname
I am trying to bind the event name plus the event start date in the cell of the calender on the date which it is occurring
However i am not able to do so
Following is my code snippet
protected void myCal_DayRender1(object sender, DayRenderEventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter cmd = new SqlDataAdapter("Select * FROM event", con);
cmd.Fill(ds, "Table");
if (!e.Day.IsOtherMonth)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
if ((dr["eventstart"].ToString() != DBNull.Value.ToString()))
{
DateTime dtEvent = (DateTime)dr["eventstart"];
if (dtEvent.Equals(e.Day.Date))
{
Label lbl = new Label();
lbl.BorderColor = System.Drawing.Color.Black;
lbl.BorderStyle = BorderStyle.Double;
lbl.Width = 100;
lbl.Height = 100;
lbl.BackColor = System.Drawing.Color.BlanchedAlmond;
lbl.Text = TextBoxName.Text + "" + TextBoxStart.Text + "" + TextBoxEnd.Text;
e.Cell.Controls.Add(lbl);
}
}
}
}
else
{
}
}
Please help someone
Ok, once again from the start. Now I think I got it. Your problem is probably caused by comparing date with time to date. To get only date without time You can use dt.Date as You can see below. You can consider loading all data on page load because of performance reasons.
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
//get data
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand =
new SqlCommand("select * from event", connection);
adapter.Fill(ds);
}
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
//mark dates in calendar
foreach (DataRow dr in ds.Tables[0].Rows)
{
DateTime dt = (DateTime)dr.Field<DateTime?>("eventstart");
if (e.Day.Date == dt.Date)
{
e.Cell.BackColor = System.Drawing.Color.Yellow;
//add event lable to day
Label lbl = new Label();
lbl.BorderColor = System.Drawing.Color.Black;
lbl.BorderStyle = BorderStyle.Double;
lbl.BackColor = System.Drawing.Color.BlanchedAlmond;
lbl.Text = "Event text";
e.Cell.Controls.Add(lbl);
}
}
}

Creating a Textbox dynamically in for loop

I was trying to create a table dynamically and put textboxes in it. Here in the following code, i was trying to create a textbox with a distinct name for each k. But only the last value of k is getting displayed in the textbox. I was wondering how i could give a name to Textbox so all are shown.
for (int k = 0; k < tblCols; k++)
{
TableCell tc = new TableCell();
TextBox txtCompanyName = new TextBox();
txtCompanyName.Text = dsmissing.Tables[0].Rows[tblCols- 1]["NewCompanyName"].ToString();
tc.Controls.Add(txtCompanyName);
}
Replace this line
dsmissing.Tables[0].Rows[tblCols- 1]["NewCompanyName"].ToString();
With
dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
I assume you are talking about ID like below.
for (int k = 0; k < tblCols; k++)
{
TableCell tc = new TableCell();
TextBox txtCompanyName = new TextBox();
txtCompanyName.Text = dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
txtCompanyName.ID = Guid.NewGuid().ToString("N");
tc.Controls.Add(txtCompanyName);
}
I think you may have meant to do this:
for (int k = 0; k < tblCols; k++)
{
TableCell tc = new TableCell();
TextBox txtCompanyName = new TextBox();
//txtCompanyName.Text = dsmissing.Tables[0].Rows[tblCols-1 ["NewCompanyName"].ToString();
txtCompanyName.Text = dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
tc.Controls.Add(txtCompanyName);
}
Surely this will work and it is easy to understand
protected void Page_Load(object sender, EventArgs e)
{
button1();
}
protected void Page_Init(object sender, EventArgs e)
{
try
{
Label lbl = new Label();
lbl.ID = "lbl_label";
lbl.Text = "Enter the values";
form1.Controls.Add(lbl);
TextBox tb = new TextBox();
tb.ID = "tbx_textbox";
form1.Controls.Add(tb);
Button bt = new Button();
bt.ID = "bt_button";
bt.Text = "click";
form1.Controls.Add(bt);
}
catch (Exception ex) { }
}
public void button1()
{
Table table = new Table();
TableRow row = null;
TableCell cell = null;
TextBox tbx1 = this.Page.FindControl("tbx_textbox") as TextBox;
try
{
int a = int.Parse(tbx1.Text);
for (int i = 0; i < a; i++)
{
row = new TableRow();
cell = new TableCell();
TextBox tx = new TextBox();
tx.ID = "box" + i.ToString();
cell.Controls.Add(tx);
row.Cells.Add(cell);
table.Rows.Add(row);
form1.Controls.Add(table);
}
}
catch (Exception ex) { }
finally
{
table = null;
}
}

Resources