Dynamically adding Table rows - asp.net

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

Related

Using a checkbox to change an existing database value

I currently have a checkbox that remains checked or unchecked based on the value in the database. I want the checkbox to be able to change dynamically, so that if it's checked upon loading the page and I change it to unchecked, it will change the database value as well as redirect to a different page. Right now I am unable to change the database value and redirect to a different page. I have autopost back set to true currently.
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection dataConnection = new SqlConnection(#"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8"))
using (SqlCommand dataCommand =
new SqlCommand("select SportHasPositions from Sport Where Sport_Id = #Sport_Id", dataConnection))
{
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "#Sport_Id";
param2.Value = Session["SportID"];
dataCommand.Parameters.Add(param2);
dataConnection.Open();
sportHasPositions = dataCommand.ExecuteScalar().ToString();
}
if (sportHasPositions == "No")
{
CheckBox1.Checked = true;
Panel1.Visible = false;
}
if (sportHasPositions == "Yes")
{
CheckBox1.Checked = false;
Panel1.Visible = true;
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == false)
{
String conString = #"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8";
SqlConnection con = new SqlConnection(conString);
//create a command behavior object
String cmdString = "UPDATE Sport SET SportHasPositions = #SportHasPositions WHERE Sport_Id = #Sport_Id";
SqlCommand cmd = new SqlCommand(cmdString, con);
SqlParameter param0 = new SqlParameter();
param0.ParameterName = "#SportHasPositions";
param0.Value = "Yes";
cmd.Parameters.Add(param0);
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "#Sport_Id";
param1.Value = Session["SportID"];
cmd.Parameters.Add(param1);
int added = 0;
try
{
con.Open();
added = cmd.ExecuteNonQuery();
}
catch (Exception err)
{
// Output.Text = err.Message;
}
finally
{
con.Close();
}
Response.Redirect("Pick Positions.aspx");
}
if (CheckBox1.Checked == true)
{
String conString = #"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8";
SqlConnection con = new SqlConnection(conString);
//create a command behavior object
String cmdString = "UPDATE Sport SET SportHasPositions = #SportHasPositions WHERE Sport_Id = #Sport_Id";
SqlCommand cmd = new SqlCommand(cmdString, con);
SqlParameter param0 = new SqlParameter();
param0.ParameterName = "#SportHasPositions";
param0.Value = "No";
cmd.Parameters.Add(param0);
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "#Sport_Id";
param1.Value = Session["SportID"];
cmd.Parameters.Add(param1);
int added = 0;
try
{
con.Open();
added = cmd.ExecuteNonQuery();
}
catch (Exception err)
{
// Output.Text = err.Message;
}
finally
{
con.Close();
}
}
}
The problem is that the asp.net life cycle runs the Page_Load event before the CheckBox1_CheckedChanged event. Since in your Page_Load, you are setting the checkbox, even if the user changed it, the Page_Load changes it back before the CheckBox1_CheckedChanged can change it in the database. To fix this you can use the Page.IsPostBack
flag so the Page_Load only sets the Checkbox on the initial page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
using (SqlConnection dataConnection = new SqlConnection(#"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8"))
using (SqlCommand dataCommand =
new SqlCommand("select SportHasPositions from Sport Where Sport_Id = #Sport_Id", dataConnection))
{
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "#Sport_Id";
param2.Value = Session["SportID"];
dataCommand.Parameters.Add(param2);
dataConnection.Open();
sportHasPositions = dataCommand.ExecuteScalar().ToString();
}
if (sportHasPositions == "No")
{
CheckBox1.Checked = true;
Panel1.Visible = false;
}
if (sportHasPositions == "Yes")
{
CheckBox1.Checked = false;
Panel1.Visible = true;
}
}
}

how to get total of all column if GridView Paging is set as “True”?

this code display total of column in each page of grid view footer I want to display total of all columns in all pages footer
if (e.Row.RowType == DataControlRowType.DataRow)
{
string deb = ((Label)e.Row.FindControl("debit")).Text;
string cred = ((Label)e.Row.FindControl("credit")).Text;
decimal totalvalue = Convert.ToDecimal(deb) - Convert.ToDecimal(cred);
amount += totalvalue;
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = amount.ToString();
Label lblDebAmount = (Label)e.Row.FindControl("debit");
Label lblCredamount = (Label)e.Row.FindControl("credit");
float debtotal = (float)Decimal.Parse(lblDebAmount.Text);
float credtotal = (float)Decimal.Parse(lblCredamount.Text);
totalPriced += debtotal;
totalPricec += credtotal;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label totallblCAmount = (Label)e.Row.FindControl("totallblDebAmount");
Label totallblCredAmount = (Label)e.Row.FindControl("totallblCredAmount");
totallblCAmount.Text = totalPriced.ToString("###,###.000");
totallblCredAmount.Text = totalPricec.ToString("###,###.000");
}
}
Why do it when the row is data bound? Why not do it when you originally bind the data?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DataTable dt = Database.GetData();
GridView1.DataSource = dt;
GridView1.DataBind();
//calculate here by manually adding up the debit/credit column from dt
//or do a separate database call that calculates the sum, ex: select sum(debits), sum(credits) from general_ledger
}
}
It makes sense to let the database do the math calculation for you. You wouldn't need to write your own custom calculation code. Just let the database's sum function handle it.
Here's a little more detail.
//Executes a SqlCommand and returns a DataTable
public class GetDataTable(SqlCommand command)
{
var dt = new DataTable();
using (var connection = new SqlConnection("connectionstring"))
{
command.Connection = connection;
connection.Open();
dt.Load(command.ExecuteReader());
}
return dt;
}
//Executes a SqlCommand and returns a scalar of type T
public static T GetScalar<T>(SqlCommand command)
{
using (var connection = new SqlConnection ("connectionstring"))
{
command.Connection = connection;
connection.Open();
var result = command.ExecuteScalar();
if (result is T)
{
return (T)result;
}
else
{
return (T)Convert.ChangeType(result, typeof(T));
}
}
}
//Load the data into the GridView, then get the credit amount and put the value in a label.
//You'll need to adjust the queries to match your schema
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var tableCommand = new SqlCommand("select columns from table");
GridView1.DataSource = GetDataTable(tableCommand);
GridView1.DataBind();
var creditCommand = new SqlCommand("select sum(stat_amount) from tablename where stat_flag='c'");
var credits = GetScalar<decimal>(creditCommand);
Label1.Text = credits;
}
}

Dynamically added checkboxs are not working in asp.net using c#?

i am adding multiple checkboxes in my asp.net page by doing this:
public static CheckBox[] chck;
on pageload:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
SqlCommand cmd = new SqlCommand("select count(CompanyName) from Stock_Company");
cmd.Connection = con;
comno = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
chck = new CheckBox[comno];
}
}
now i have a function which is generating the checkboxes :
public void generatecheckbox1()
{
con.Open();
SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
chck[i] = new CheckBox();
chck[i].ID = "chck" + Convert.ToString(i);
chck[i].Text = dt.Rows[i]["CompanyName"].ToString();
pnlcom1.Controls.Add(chck[i]);
pnlcom1.Controls.Add(new LiteralControl("<br />"));
}
}
and i am calling this on a combobox event:
protected void ddluserwebser_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddluserwebser.SelectedItem.Text == "Custom")
{
generatecheckbox1();
}
}
as far as this all are working fine ... but in a button click i want to get the select checkbox's text which i am not getting
i made a function :
public string getbsecompany()
{
string companyname = "";
string bsetricker = "";
con.Open();
SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (chck[i].Checked == true) **THE PROBLEM IS HERE**
{
companyname = chck[i].Text;
con.Open();
SqlCommand cmdd = new SqlCommand("select BSETickerCode from Stock_Company where CompanyName='" + companyname + "'");
cmdd.Connection = con;
bsetricker += bsetricker + "+" + cmdd.ExecuteScalar();
con.Close();
}
}
return bsetricker;
}
and i am calling it here:
protected void btnusersave_Click(object sender, EventArgs e)
{
string bsetricker = "";
bsetricker = getbsecompany();
}
the problem is i am not getting the checked box's text. when i am checking if (chck[i].Checked == true) i am gettin false and all checkboxes are checked.
What should i do now?
any help
The dynamic controls should added to page in On_Init() for each time if you want it display in page.
Else there's nothing you can get.
Plus, better not use a static value to contains checkBox List, it will cause problem when multi user access same page. You can save them in session or try this.Form.FindControls()

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);
}
}
}

Resources