asp.net datalist update to another page - c#

I am using datalist in asp.net c#, to display data from database and perform delete. But also at this table I have an other button "edit" which I want to get the id of item and go to another page with a form that is prefilled with data about that item. The problem is that I am new at asp.net and I dont know how to get data form one page to another (like id).
public partial class DataList : System.Web.UI.Page
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
try
{
if(!IsPostBack)
{
Bind();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
public void Bind()
{
SqlConnection con = new SqlConnection(connection);
SqlDataAdapter da = new SqlDataAdapter("select * from artikulli", con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
con.Close();
datalist2.DataSource = ds.Tables[0];
datalist2.DataBind();
}
protected void Datalist1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox txtTema = e.Item.FindControl("txtTema") as TextBox;
SqlConnection conn = new SqlConnection(connection);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "Insert into artikulli(tema) values (#tema)";
command.Parameters.Add("#tema", SqlDbType.VarChar, 250).Value = txtTema.Text;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
}
}
protected void Datalist1_EditCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Edit"))
{
Response.Redirect("EditArtikull3.aspx");
}
}
protected void datalist1_CancelCommand(object source, DataListCommandEventArgs e)
{
datalist2.EditItemIndex = -1;
Bind();
}
protected void datalist1_UpdateCommand(object source, DataListCommandEventArgs e)
{
if(e.CommandName.Equals("Update"))
{
}
}
protected void datalist2_DeleteCommand(object source, DataListCommandEventArgs e)
{
Label lblId = e.Item.FindControl("lblId") as Label;
SqlConnection conn = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "Delete from artikulli where id=#id";
cmd.Parameters.Add("#id", SqlDbType.Int, 11).Value = lblId.Text;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Bind();
}
}
I really need some help

One of the easiest ways to pass data is through the QueryString. Consider for example..
Label lblId = e.Item.FindControl("lblId") as Label;
string id=lblId.Text;
Response.Redirect("EditArtikull3.aspx?id="+id);
Then on the EditArtikull3 page, in the Page_Load method, check for that QueryString parameter and load data accordingly.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
if(!String.IsNullOrEmpty(Request.QueryString["id"]))
{
string id=Request.QueryString["id"];
//load data based on the id
}
else
{
//tell the user they can't navigate directly to this page.
}
}
}

Pass it as querystring eg
Response.Redirect("EditArtikull3.aspx?Id=yourId");
You can refer to
http://msdn.microsoft.com/en-us/library/vstudio/6c3yckfw(v=vs.100).aspx

One alternative would be to pass the id in the URL as in:
protected void Datalist1_EditCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Edit"))
{
Response.Redirect(string.Format("EditArtikull3.aspx?id={0}",((DataRowView)e.Item.DataItem).Row.ItemArray[0].ToString()); // where [0] is the index of the column containing the item ID
}
}
Then on the EditArtikull3.aspx page read it from the QueryString
Page_Load(...)
{
if(!IsPostback)
{
string id = Request.QueryString["id"] as string;
if(id!=null)
{
//query the database and populate the data
}
}
}

Query string method:
Response.Redirect("EditArtikull3.aspx?id=yourId");
In redirected page..
protected void Page_Load(object sender, EventArgs e)
{
string id=Request.QueryString["id"];
}

Related

How to pass the parameter of a stored procedure on page load

How to pass the parameter of a stored procedure on page load? It needs to be an overload.
protected void bind(DateTime dt)
{
SqlConnection cn = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "HeadCount03";
cmd.Parameters.AddWithValue("#years", ddlyear.SelectedValue);
cmd.Parameters.AddWithValue("#months", ddlMonths.SelectedValue);
cmd.Parameters.AddWithValue("#Cal", Convert.ToInt32(dt));
cmd.Connection = cn;
try
{
cn.Open();
GridView2.EmptyDataText = "No Records Found";
GridView2.DataSource = cmd.ExecuteReader();
GridView2.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cn.Close();
cn.Dispose();
}
if (!IsPostBack)
{
bind();
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
DateTime Cal = new DateTime(
Convert.ToInt32(ddlyear.SelectedValue),
Convert.ToInt32(ddlMonths.SelectedValue),
1);
bind(Cal);
}
Im trying to figure out what you ment by this question, the way I see it you are gonna need a Form_load event.
private void Form_Load(object sender, EventArgs e)
{
bind(DateTime.Now());
}
Althought you should really add some more information. For instance, what does this line mean?
cmd.CommandText = "HeadCount03";
EDIT
Adding parameters on an event can be done like so:
private void Form_Load(object sender, EventArgs e, string parameter)
{
//whatever
}
Call it like this using lambda expressions:
(sender, e) => Form_Load(sender, e, parameter);

Attempting to get a count of records from gridview based on a selected date from dropdownlist but cant?

The problem lies that upon selection of the date in the dropdown it will give the count of the LAST selection, not the current.
I am a novice and the only thing I can think of is some type of postback issue? The gridview populates fine with the records selected by the DDL, so I just cant get my head around why the count that is rendered is the previous selection.
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e)
{
lblRecordCounter.Text = "";
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT (*) FROM gescdb" +
"WHERE ClassDate=" + ddlClassDate.Text, conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
GridRegistrants.DataSource = reader;
GridRegistrants.DataBind();
reader.Close();
}
catch
{
}
finally
{
conn.Close();
lblRecordCounter.Text = GridRegistrants.Rows.Count.ToString();
}
In your Page_Load method you do the same, right? You have to move that code into following block:
if (!IsPostBack){
//Your code is here
}
Your DropDownList:
<asp:DropDownList ID="ddlClassDate" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlClassDate_SelectedIndexChanged" />
Your code behind:
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack){
BindDDL();
BindGrid(ddlClassDate.SelectedValue);
}
}
protected void BindDDL(){
//Bind Your dropdownlist here
}
protected void BindGrid(string ddate){
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString);
SqlCommand comm = new SqlCommand("select * from gescdb where ClassDate = #date", conn);
comm.Parameters.Add("#date", SqlDbType.VarChar).Value = ddate;
try
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
sda.Fill(ds);
GridRegistrants.DataSource = ds;
GridRegistrants.DataBind();
}
catch
{
//...
}
finally
{
conn.Close();
}
}
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e){
BindGrid(ddlClassDate.SelectedValue);
}

Grid not updating on edit button press

I have a gridview.
I am trying to edit it, but value is not getting updated.
My Code:
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");
BindGrid();
}
private void BindGrid()
{
try
{
da = new SqlDataAdapter("select * from emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
string eName = ((TextBox)row.Cells[2].Controls[0]).Text.ToString().Trim();
try
{
con.Open();
cmd = new SqlCommand("update emp set empName='" + eName + "'", con);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
GridView1.EditIndex = -1;
}
catch (Exception ex)
{
}
finally
{
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
}
Please let me know the point where i am making mistake.
use BindGrid() inside Page.IsPostBack as follows on Page_Load event
if(!Page.IsPostBack)
{
BindGrid();
}
Edit 1
I think the following line should work
BindGrid();
GridView1.EditIndex = -1;
As it is not working see is there any error in the catch block.
catch (Exception ex)
{
Response.Write(ex.Message);
}
See weather there is some error or not?
You can try like this...becuase...when you click on edit button your pageload event is called first....and on pageload you bind the gridview again...so its edit index is lost because it binded again...and it set edit index to -1 each and everytime...
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");
BindGrid();
}
}
Edit1: OP After Update Edit Mode Doesnt goes..
You Have to Set gridview Edit index before Its binding like below....
try
{
con.Open();
cmd = new SqlCommand("update emp set empName='" + eName + "'", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;//Put this line Before the Binding of GridView
BindGrid();
}

Update button keeps updating on click of Refresh in IE

I have a form wherein I populate content using stored procedure and I perform update actions on the content. Now my update button works fine. My problem is that each time I click on 'refresh' button in IE, the content gets updated and I don't want that to happen. I am new to .Net and all this ViewState stuff. Any help is appreciated..
Here is my code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void BindGridView()
{
string constring = ConfigurationManager
.ConnectionStrings["shaConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("spd_pc", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.Add("#city", SqlDbType.VarChar).Value = txt_city.Text;
con.Open();
IDataReader idr = cmd.ExecuteReader();
GridView1.DataSource = idr;
GridView1.DataBind();
idr.Close();
con.Close();
}
}
}
protected void Button1_click(object sender, EventArgs e)
{
BindGridView();
}
private void DeleteRecords(int id)
{
string constring = ConfigurationManager.
ConnectionStrings["shaConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("del_pc", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
conn.Open();
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = id;
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
protected void ButtonDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
CheckBox chkb = (CheckBox)row.FindControl("CheckBox1");
if (chkb.Checked)
{
int id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
if (!(id.Equals(System.DBNull.Value)))
{
DeleteRecords(id);
}
}
}
BindGridView();
}
protected void Button2_Click(object sender, EventArgs e)
{
if (!IsCallback)
{
string active = "active";
string inactive = "inactive";
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkb = (CheckBox)row.FindControl("CheckBox1");
if (chkb.Checked)
{
int id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
string status = row.Cells[5].Text;
if (!(id.Equals(System.DBNull.Value)))
{
if ((String.Equals(active, status)))
UpdateRecords(id);
if ((String.Equals(inactive, status)))
UpdateRecords(id);
}
}
}
}
}
private void UpdateRecords(int id)
{
string constring = ConfigurationManager.
ConnectionStrings["shaConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("upd_pc", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
conn.Open();
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = id;
cmd.ExecuteNonQuery();
conn.Close();
}
}
BindGridView();
}
}
yes, this will happen. the problem is you are refreshing the post event of the button click. the solution is to redirect back to page after the update is complete.
button_click(...)
{
//save to db
Response.Redirect(Request.Referrer);
}
or something like that.
Now if the user clicks refresh it will submit the GET request to load the page, rather the POST to issue the button click event.
If you search for Post Get Redirect (or something like that) you will find lots of articles on the topic. describing both the situation you encountered and why this solution works.

Couldn't get the values from the cells in GridView using check box in ASP.net

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (s.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
rdr.Close();
}
catch
{
conn.Close();
}
}
I have a button like this. But I'm not able to get the values of the cells(Label is not getting appended).
protected void Button1_Click(object sender, EventArgs e)
{
string[] FID={};
int j=0;
foreach (GridViewRow di in GridView1.Rows)
{
HtmlInputCheckBox chkBx = (HtmlInputCheckBox)di.FindControl("CheckBox1");
if ( chkBx != null && chkBx.Checked)
{
FID[j] += di.Cells[2].Text;
j++;
Label1.Text += di.Cells[2].Text;
//Label lbl = (Label)di.FindControl("Id");
//Response.Write(lbl.Text + "<br>");
}
}
}
Put your page load code under if(!IsPostBack){yourCode....} so when you click the button your page load event will be called before the click handler and it will rebind the gridview.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (s.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
rdr.Close();
}
catch
{
conn.Close();
}
}
}
i think if you can debug the code,
you can find and solve your problem easily.
First, check is your loop really do.
Second, is Cell[2] is really what you want to get data.(I doubt that)
Hope it works!

Categories

Resources