How to solve Column 'Policy_No' does not belong to table? - asp.net

I have a simple interface which has a text box, button and a gridview. I want to display the number in the gridview when click the button. But I get an ArgumentException saying "Column 'Policy_No' does not belong to table". what should I do to solve it. Here I have added the code below.
Button Click Event
protected void btnAdd_Click(object sender, EventArgs e)
{
dt = new DataTable();
dr = dt.NewRow();
dr["Policy_No"] = txtPolicy.Text.Trim();
dt.Rows.Add(dr);
grdPolicy.DataSource = dt;
grdPolicy.DataBind();
}
Page Load code
protected void Page_Load(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("Policy_No", typeof(string)));
if (!IsPostBack)
{
loadCompetitionsNames();
}
}

You are creating new DataTable inside btnAdd_Click that doesn't have column Policy_No
protected void btnAdd_Click(object sender, EventArgs e)
{
//dt = new DataTable(); Remove this line
dr = dt.NewRow();
dr["Policy_No"] = txtPolicy.Text.Trim();
dt.Rows.Add(dr);
grdPolicy.DataSource = dt;
grdPolicy.DataBind();
Session["PolicyTable"] = dt;
}
protected void Page_Load(object sender, EventArgs e)
{
if(Session["PolicyTable"] !=null)
dt = Session["PolicyTable"] as DataTable;
else
dt = new DataTable();
if (!dt.Columns.Contains("Policy_No"))
dt.Columns.Add(new DataColumn("Policy_No", typeof(string)));
if (!IsPostBack)
{
loadCompetitionsNames();
}
}

Add column definition at Button Click Event
public DataTable GetGridData()
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("Policy_No", typeof(string)));
dr = dt.NewRow();
dr["Policy_No"] = txtPolicy.Text.Trim();
dt.Rows.Add(dr);
return dt;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
grdPolicy.DataSource = GetGridData();
grdPolicy.DataBind();
}
Remove initialization of dt(DataTable) from page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadCompetitionsNames();
}
}
You can use session to keep dt data on page postback

Related

ViewState for private string with button

I have gridview with a Rowcommand event that let's me get the column ActivityID cell value and puts it in a private string called ActivityIDString.
private string ActivityIDString; // To be used in btUpdate
protected void gwActivity_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Page") return;
GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);
string ActivityID = row.Cells[1].Text;
ActivityIDString = ActivityID;
}
This all works when the row is selected however when i press my "btUpdate" button the ActivityIDString becomes NULL.
protected void btUpdate_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("sp_tblActivityUpdate", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ActivityID", ActivityIDString);
con.Open();
cmd.ExecuteNonQuery();
BindGridviewActivity();
}
}
I understand the issue and why it becomes NULL but I don't know exactly how to solve this issue and where to use the ViewState.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["ActivityIDStringText"] = "ActivityIDString"; // <-- SHOULD I CREATE THIS?????
}
}
this method should be something like this
protected void gwActivity_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Page") return;
GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);
string ActivityID = row.Cells[1].Text;
ViewState["ActivityIDString"] = ActivityID;
}
then retrieve it in button method
protected void btUpdate_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
string ActivityIDString= Convert.ToString(ViewState["ActivityIDString"]);
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("sp_tblActivityUpdate", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ActivityID", ActivityIDString);
con.Open();
cmd.ExecuteNonQuery();
BindGridviewActivity();
}
}
You can use Session here. Whenever a row is selected add the ID in the session and retrieve the value of the session object in the btUpdate click event and then null the session .
Inside the gwActivity_RowCommand()
Session["ActivityId"] += ";ActivityId";
and inside btUpdate_Click()
if(Session["ActivityId"]!=null){
var ActivityIds = Session["ActivityId"].Split(';'); // For Mulitple Ids if Required
Session["ActivityId"] = null;
}

Radio button selected index not working

So I have a sipme ASP.NET Web Page that prints the info of one's gender stacked dynamically in a radio button list:
protected void Page_Load(object sender, EventArgs e)
{
String[] genders = new String[2];
genders[0] = "Male";
genders[1] = "Female";
RadioButtonList1.DataSource = genders;
RadioButtonList1.DataBind();
RadioButtonList1.Items.Add(new ListItem("Neutral", "Zero"));
}
protected void Button1_Click(object sender, EventArgs e)
{
lblName.Text = txtName.Text;
lblSurname.Text = txtSurname.Text;
lblEmail.Text = txtMail.Text;
Panel1.Visible = true;
if (RadioButtonList1.SelectedIndex==0) lblGender.Text = "Male";
else lblGender.Text = "Female";
}
However when I launch the site no matter what I select it always writes female it's like the RadioButtonList1.SelectedIndex==0 isn't working.
Any ideas?
Bind radiobuttonlist in page_Load with !IsPostBack condition or your radiobuttonlist will bind every time you post your page. So your radiobuttonlist is reset to index -1 when you click the button_click.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
String[] genders = new String[2];
genders[0] = "Male";
genders[1] = "Female";
RadioButtonList1.DataSource = genders;
RadioButtonList1.DataBind();
RadioButtonList1.Items.Add(new ListItem("Neutral", "Zero"));
}
}

keep dataTable present through page navigating aspx.net

i have data Table which is dynamically created and is bind to grid View and the page have a button which is redirecting user on another page when is clicked. That's page one.Now when user is redirected on page 2, and if he want to get back on page 1, I want to be present data Table when page load.Some example code how to do that?
page1
protected void Page_Load(object sender, EventArgs e)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
GridView2.DataSource = dtCurrentTable();
GridView2.DataBind();
}
public void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Page2.aspx");
}
//method for insert dataTable in database
public void Button2_Click(object sender, EventArgs e)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
Session["Markici"] = dtCurrentTable;
dtCurrentTable = (DataTable)Session["Markici"];
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
SqlCommand cmd = new SqlCommand("InsertMarkica",conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "InsertMarkica";
foreach (DataRow dr in dtCurrentTable.Rows)
{
cmd.Parameters.Clear();
//SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#FirmaID", dr["FirmaID"]);
cmd.Parameters.AddWithValue("#Godina", dr["Godina"]);
cmd.Parameters.AddWithValue("#Kasa", dr["KasaID"]);
cmd.Parameters.AddWithValue("#Masa", dr["Masa"]);
cmd.Parameters.AddWithValue("#MarkicaID", dr["MarkicaID"]);
cmd.Parameters.AddWithValue("#Datum", dr["Datum"]);
cmd.Parameters.AddWithValue("#VrabotenID", dr["VrabotenID"]);
cmd.Parameters.AddWithValue("#Smena", dr["Smena"]);
cmd.Parameters.AddWithValue("#VkIznos", dr["VkIznos"]);
cmd.Parameters.AddWithValue("#VkDanok", dr["VkDanok"]);
cmd.ExecuteNonQuery();
cmd.Connection = conn;
}
page2
public void Button2_Click(object sender, EventArgs e)
{
Reponse.Redirect("Page1.aspx");
//Now when is redirected on page1, it should be present data Tale,
//needed that data Table for inserting records in database
}
You can create a session variable as follow
protected void Page_Load(object sender, EventArgs e)
{
dtCurrentTable = (DataTable)ViewState["Markici"];
Session["Markici"]=dtCurrentTable;
GridView2.DataSource = dtCurrentTable();
GridView2.DataBind();
}
Not the value of Session["Markici"] will be available in the current session on any page. You need to cast and use it as follow
dtCurrentTable = (DataTable)Session["Markici"];

Adding a checkbox in a table cell

Is this possible?
I have a table with user accounts retrieved from a database. Then at the start of each column I would like to add a checkbox which if selected will select the account. I tried experimenting with it and I can't seem to put the checkbox inside the table. How can I do this?
You can try this:
const int ColumnSelect = 0;
protected void Page_Load(object sender, EventArgs e)
{
//Get real data here.
DataTable dt = new DataTable();
dt.Columns.Add("count");
dt.Rows.Add(dt.NewRow());
dt.Rows[0][0] = "5";
GridView1.Columns.Add(new TemplateField());
BoundField b = new BoundField();
GridView1.Columns.Add(b);
b.DataField = "count";
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Header)
{
e.Row.Cells[ColumnSelect].Controls.Add(new CheckBox());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in GridView1.Rows)
{
//Could also use (CheckBox)row.Cells[ColumnSelect].FindControl if you give the checkboxes IDs when generating them.
CheckBox cb = (CheckBox)row.Cells[ColumnSelect].Controls[0];
if (cb.Checked)
{
//Do something here.
}
}
}

Using DropDown_SelectedIndexChanged to bind gridview, but paging is not working

I have a DropDownList which is having few list items. Every time I select any item, based on it I am binding a gridview, hence resulting gridview depends on my selection. Some results are exceeding the pagesize hence I need to navigate on 2nd page in GridView, however the GridView is disappeating when I am selecting 2nd page.
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
SqlConnection con = new SqlConnection(constr);
con.Open();
string str = string.Empty;
str = "SELECT * FROM Table1";
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
adp.Fill(ds, "myds");
BusinessKPIGrid.DataSource = ds;
BusinessKPIGrid.DataBind();
}
protected void OnGridViewPaging(object sender, GridViewPageEventArgs e)
{
//I know I need to bind the gridview here, but how ?
BusinessKPIGrid.PageIndex = e.NewPageIndex;
BusinessKPIGrid.DataBind();
}
I don't know how to bind the gridview in paging event, since I do not have any separate binding function.
there is a separate function for page event for grid view..create separate method for binding grid & call that method on pageindexchange event..
protected void BusinessKPIGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BusinessKPIGrid.PageIndex = e.NewPageIndex;
bindyourgrid();
}
try this
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
SqlConnection con = new SqlConnection(constr);
con.Open();
string str = string.Empty;
str = "SELECT * FROM Table1";
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
adp.Fill(ds, "myds");
ViewState["ds"]=ds;
BusinessKPIGrid.DataSource = ds;
BusinessKPIGrid.DataBind();
}
protected void OnGridViewPaging(object sender, GridViewPageEventArgs e)
{
//I know I need to bind the gridview here, but how ?
BusinessKPIGrid.PageIndex = e.NewPageIndex;
BusinessKPIGrid.DataSource = (DataSet)ViewState["ds"];
BusinessKPIGrid.DataBind();
}
From DDL_SelectedIndexChanged if you are searching some thing then use 'PageIndexChanging' and set the page size for it
protected void gvworker_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvworker.PageIndex = e.NewPageIndex;
//result got from ddl list i.e bind your data set
}

Resources