How to get a table on a new web page when a button is Clicked - asp.net

This is my one tag:
<asp:Button ID="button" runat="server" Text="ShowOrder" onclick="newTab" />
This is my 'aspx.cs' which will be called when button is clicked
protected void newTab(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?id="+txtSearchCustomerByID.Value);
}
What I want is to print my sql table on loaded web tab (new page) when it gets loaded.
My stored procedure is displaying the data of my table where id is equal to "id entered by user in textbox".
Now,
protected void Page_Load(object sender, EventArgs e)
{
int id_no = int.Parse(Request.QueryString["id"]);
if (Page.IsPostBack)
{
showOrders(id_no);
}
}
Now what should I have in 'Default2.aspx' so that I will get my table by using,
public void showOrders(int id)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand("showOrdersSP", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", id);
con.Open();
.......
}
}
I need to use DataTable
So simply when I clicked, I will get data table on new page

You can refer below code:
public void showOrders(int id)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
DataTable dt = new DataTable();
SqlParameter[] p1 = new SqlParameter[1];
p1[0] = new SqlParameter("#id", id);
dt= getRecords_table("showOrdersSP", p1); // you will get your DataTable here
}
}
// Common Method for FillYour Tables
private DataTable getRecords_table(string spname, SqlParameter[] para)
{
string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["connName"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(connectionstring);
SqlDataAdapter ad = new SqlDataAdapter(spname, con);
ad.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
ad.SelectCommand.Parameters.AddRange(para);
con.Open();
ad.Fill(dt);
con.Close();
return dt;
}
Hope it will helps you
Thanks

Related

lable is not showing any output for the dropdown list selection

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LibraryConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlbookavail.Items.Add(new ListItem("select", "-1"));
ddlbookavail.AppendDataBoundItems = true;
SqlCommand cmd = new SqlCommand("select * from tblbookinfo", con);
con.Open();
ddlbookavail.DataSource = cmd.ExecuteReader();
ddlbookavail.DataTextField = "Name";
ddlbookavail.DataValueField = "Id";
ddlbookavail.DataBind();
con.Close();
txtdate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
}
in my design page i put the sql datasource from data and got this connection srting

ASP.NET Listview.selectedindex property goes crazy

I'm deleting a single database record from a listview and after deleting I try to navigate in my listview using listView1.selectedindex property, but I have noticed that it highlights the incorrect record (for example I set listView1.selectedindex to 1 but it displays a record which has index 0) . What is wrong? Please help!
protected void deleteButton_Click(object sender, EventArgs e)
{
int id = int.Parse(((Label)ListView1.Items[ListView1.SelectedIndex].FindControl("idLabel")).Text);
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
BindDataFromBaseToListView method looks so:
private void BindDataFromBaseToListView()
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("select * from Employee", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
ListView1.DataSourceID = null;
ListView1.DataSource = dTable;
ListView1.DataBind();
}
conn.Close();
}
Instead of using deleteButton_Click event you could use your ListView's OnItemCommand event to get the selected row values and delete the item that you want like the code below:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "delete")
{
int id = 0;
if(int.TryParse((e.Item.FindControl("idLabel") as Label).Text, out id))
{
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
}
}
And on your control's element will look like this:
<asp:ListView ID="ListView1" runat="server" OnItemCommand="ListView1_ItemCommand" .. >
...
<ItemTemplate>
<asp:Button runat="server" CommandName="delete" Text="Delete" ID="DeleteButton" />
...
Let me know if you still have issue with it.

Making code duplication to refresh the gridview in asp.net

I am trying to update the gridview after updating some data. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = University.GetConnectionString();
con.Open();
string query = "select [ID],[Name],[Surname],[level] from StudentTable order by ID";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
studentLevel.DataSource = dt;
studentLevel.DataBind();
con.Close();
}
protected void studentLevel_RowCommand(object sender, GridViewCommandEventArgs e)
{
int row = -1;
int.TryParse(e.CommandArgument as string, out row);
GridViewRow gdrow = studentLevel.Rows[row];
DataRow dr = ((DataTable)studentLevel.DataSource).Rows[gdrow.DataItemIndex];
string id = dr["ID"].ToString();
Student student = new Student(Convert.ToInt32(id), "", "", "", "", "", "", "");
if (e.CommandName == "Undergraduate")
student.setLevelRole(new UnderGraduateStudent());
else if (e.CommandName == "Graduate")
student.setLevelRole(new GraduateStudent());
student.writeLevelRole(id);
SqlConnection con = new SqlConnection(); //HERE IS DUPLICATION
//refresh the gridview on the page
con.ConnectionString = University.GetConnectionString();
con.Open();
string query = "select [ID],[Name],[Surname],[level] from StudentTable order by ID";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
studentLevel.DataSource = dt;
studentLevel.DataBind();
con.Close();
}
The problem is, if i do not write the last 12 lines of the code, which is the same code as page_load method, the gridview does not refresh itself on the page. Waht can i do to avoid this?
Thanks
You should provide a method that loads the data and databinds the GridView, for example DataBindGrid:
private void DataBindGrid()
{
using(var con = new SqlConnection(University.GetConnectionString()))
{
con.Open();
string query = "select [ID],[Name],[Surname],[level] from StudentTable order by ID";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
studentLevel.DataSource = dt;
studentLevel.DataBind();
}
}
Then you can call it from wherever you need. If you want to change something you have only one place to maintain which is less error-prone.
Note that you should databind the GridView only if(!IsPostBack) if you use ViewState(default):
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback))
DataBindGridView();
}
and in RowCommand
protected void studentLevel_RowCommand(object sender, GridViewCommandEventArgs e)
{
// ... update student ... then
DataBindGridView();
}

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 ActiveTabChanged for AJax Tab container

How to fire ActiveTabChanged for TabContainer. I have written a code to populate the TabPanel HeaderText from the database and this is my code
public partial class dynamicTab : System.Web.UI.Page
{
string strCon = ConfigurationManager.ConnectionStrings["SqlCon"].ConnectionString.ToString();
TabContainer ajxTab;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// createTab();
pnlDynamic.Controls.Add(ajxTab);
ajxTab_ActiveTabChanged(ajxTab, EventArgs.Empty);
}
}
private void ajxTab_ActiveTabChanged(TabContainer ajxTab, EventArgs eventArgs)
{
SqlConnection con = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand("select * from Employee where DeptID='" + ajxTab.ActiveTab.ID.ToString() + "'", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
GridView grd = new GridView();
grd.AutoGenerateColumns = true;
grd.DataSource = ds;
grd.DataBind();
pnlDynamic.Controls.Add(grd);
}
protected void page_init(object sender, eventargs e)
{
createtab();
}
private void createTab()
{
SqlConnection con = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand("select DeptID,DepartmentName from Department", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
ajxTab = new AjaxControlToolkit.TabContainer();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
TabPanel pnl = new TabPanel();
pnl.HeaderText = ds.Tables[0].Rows[i]["DepartmentName"].ToString();
pnl.ID = ds.Tables[0].Rows[i]["DeptID"].ToString();
ajxTab.Tabs.Add(pnl);
ajxTab.ActiveTabIndex = 0;
}
}
}
For the first time ActiveTabChanged fired perfectly , but when I click on the second tab ActiveTabChanged is not getting fired. I tried by setting ajxTab.AutoPostBack=true but the tab container is not getting visible when the event occurs.
This is my sample output
On clicking computers I would like to load grid with those details so can some one help me
You can bind the content of each tab in the OnActiveTabChanged event
OnActiveTabChanged="TabContainer1_ActiveTabChanged"
AutoPostBack="true"

Resources