Gridview doesn't refresh after deleting a row - asp.net

I have a GridView in an UpdatePanel.
When I add a row, it gets updated right away. The problem is that, when I delete a row, it doesn't update the GridView.
What can be done?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["EventId"] != null)
{
ExtractEventData();
GridView1.DataSourceID = "SqlDataSource1";
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string CS =
ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spInsertComment", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Comment", txtComment.Text);
cmd.Parameters.AddWithValue("#Eventid", lblEventId.Text);
cmd.Parameters.AddWithValue("#UserId", Session["UserId"].ToString());
cmd.ExecuteNonQuery();
txtComment.Text = "";
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int id = Int32.Parse(e.CommandArgument.ToString());
string CS = ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand(
"Delete from tblEventComments WHERE CommentId = #CommentId", con);
cmd.Parameters.AddWithValue("#CommentId", id);
cmd.ExecuteNonQuery();
GridView1.DataSourceID = "";
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
}
I have also tried removing the datasource1 connection from GridView and then re-assigned it. Still it doesn't seem to work, the way I need it to.
I don't think you will need the GridView markup here, however you can ask for it if necessary.

According to this post, you should delete the row using GridView.DeleteRow method.

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

!IsPostBack returns always true

I am trying to implement search operation for my gridview.When I load my page first time !IsPostBack works fine but when I click on the search button my page loads again and !IsPostBack returns true value.So, I was not able to perform my search operation
this is my code.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
((Label)Master.FindControl("Label1")).Text = (string)Session["sname"];
fillData();
}
}
public void fillData()
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM EBR_Supplier where DeleteFlag=" + 0 + " ORDER BY RowId ASC", con);
SqlDataAdapter adap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
fillData();
}
protected void search_Click(object sender, EventArgs e)
{
string id = txtid.Text;
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM EBR_Supplier where DeleteFlag=" + 0 + " and SupplierId='" + id + "' ORDER BY RowId ASC", con);
SqlDataAdapter adap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
I have found the solution myself I have a form control on my master page.I removed that it helped me.I thank you all for giving time to my question.

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

How to get modified value of TextBox

This is PageLoad code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//DropDownList Binding through bussiness logic
Bussiness_logic.DropDownList_Bind(DDL_U, "SHORT_DESC", "UNIT_CODE", "UNIT_SOURCE");
Bussiness_logic.DropDownList_Bind(DDL_Branch, "TYPE_DESC", "TYPE_CODE", "BRANCH_SOURCE");
}
if (Request.QueryString["File"] != null)
{
string fileNo = Request.QueryString["File"].ToString();
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("LINK_DATA", Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE", fileNo);
SqlDataReader dtr = com.ExecuteReader();
if (dtr.HasRows)
{
dtr.Read();
{
TxtFile.Text = dtr["FILE_NO"].ToString();
DDL_Branch.SelectedValue = dtr["TYPE_DESC"].ToString();
TxtSub.Text = dtr["SUBJECT"].ToString();
DDL_U.SelectedValue = dtr["SHORT_DESC"].ToString();
}
}
Bussiness_logic.CloseConnection();
Label1.Text = "";
}
}
I have get value of QueryString from another page and file my fields according to File variable fetching data from database corresponding to File data .Fields(Two Textbox and two DropDwnList) are filling correctly but when i modify data in textbox or DDL and Click on Update button then it is not updating data .
Update Button code
protected void BtnUpdate_Click(object sender, EventArgs e)
{
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("UPDATE_DATA",Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE_NO", TxtFile.Text);
com.Parameters.AddWithValue("#SUB",TxtSub.Text);
com.Parameters.AddWithValue("#UNIT",DDL_U.SelectedValue);
com.Parameters.AddWithValue("#BRANCH",DDL_Branch.SelectedValue);
com.ExecuteNonQuery();
Label1.Text = "Action perfomed successfully !!!";
Bussiness_logic.CloseConnection();
Bussiness_logic.Empty_Control(TxtFile, TxtSub, DDL_U, DDL_Branch);
//GridView1.Visible = false;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//DropDownList Binding through bussiness logic
Bussiness_logic.DropDownList_Bind(DDL_U, "SHORT_DESC", "UNIT_CODE", "UNIT_SOURCE");
Bussiness_logic.DropDownList_Bind(DDL_Branch, "TYPE_DESC", "TYPE_CODE", "BRANCH_SOURCE");
if (Request.QueryString["File"] != null)
{
string fileNo = Request.QueryString["File"].ToString();
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("LINK_DATA", Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE", fileNo);
SqlDataReader dtr = com.ExecuteReader();
if (dtr.HasRows)
{
dtr.Read();
{
TxtFile.Text = dtr["FILE_NO"].ToString();
DDL_Branch.SelectedValue = dtr["TYPE_DESC"].ToString();
TxtSub.Text = dtr["SUBJECT"].ToString();
DDL_U.SelectedValue = dtr["SHORT_DESC"].ToString();
}
}
Bussiness_logic.CloseConnection();
Label1.Text = "";
}
}
}
Put Your second if also in first if.Because when you click update button than your page load event fire first.Means your textbox value again set from textbox.So putting your second if inside first if stop setting the textbox value from database on postbask,

Error in insert the value into database in asp.net ,c# of registration form

Code show as follow:
nection cnn = new SqlConnection("Data Source=USER-PC\\KHEMCHAND;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
cnn.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into tbl_ragistration values(#f_name,#l_name,#email_id,#pass_word,#[date of brth],#add_ress,#gender)", cnn);
cmd.Parameters.AddWithValue("#f_name", Texfname.Text);
cmd.Parameters.AddWithValue("#l_name", Texlname.Text);
cmd.Parameters.AddWithValue("#email_id", Texemail.Text);
cmd.Parameters.AddWithValue("#pass_word", Texpwd.Text);
cmd.Parameters.AddWithValue("#[date o birth]", Texdbt.Text);
cmd.Parameters.AddWithValue("#add_ress", Texadd.Text);
cmd.Parameters.AddWithValue("#gender", DropDownList1.Text);
cmd.ExecuteNonQuery();
cnn.Close();
}
Change cmd.Parameters.AddWithValue("#[date o birth]", Texdbt.Text); to cmd.Parameters.AddWithValue("#[date of birth]", Texdbt.Text); in Insert parameters value assigning. And also dont open the connection in the page load event. Befor executing the query open the connection, Execute the query and then close the connection for a better approach
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
You can try with below way, I hope this is good approach (though database execution should put in Data Access Layer), thanks for your time.
public string ConnectionString
{
get
{
return "Data Source=USER-PC\\KHEMCHAND;Integrated Security=True";
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection cnn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd =new SqlCommand(
"insert into tbl_ragistration values(#f_name,#l_name,#email_id,#pass_word,#[date of brth],#add_ress,#gender)"
,cnn))
{
cmd.Parameters.AddWithValue("#f_name", Texfname.Text);
cmd.Parameters.AddWithValue("#l_name", Texlname.Text);
cmd.Parameters.AddWithValue("#email_id", Texemail.Text);
cmd.Parameters.AddWithValue("#pass_word", Texpwd.Text);
cmd.Parameters.AddWithValue("#[date o birth]", Texdbt.Text);
cmd.Parameters.AddWithValue("#add_ress", Texadd.Text);
cmd.Parameters.AddWithValue("#gender", DropDownList1.Text);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
}
make sure you declare also the column names on your insert statement:
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection cnn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd =new SqlCommand(
"insert into tbl_ragistration (f_name,l_name,email_id,pass_word,[date of brth],add_ress,gender) values (#f_name,#l_name,#email_id,#pass_word,#dateofbrth,#add_ress,#gender)"
,cnn))
{
cmd.Parameters.AddWithValue("#f_name", Texfname.Text);
cmd.Parameters.AddWithValue("#l_name", Texlname.Text);
cmd.Parameters.AddWithValue("#email_id", Texemail.Text);
cmd.Parameters.AddWithValue("#pass_word", Texpwd.Text);
cmd.Parameters.AddWithValue("#dateofbirth", Texdbt.Text);
cmd.Parameters.AddWithValue("#add_ress", Texadd.Text);
cmd.Parameters.AddWithValue("#gender", DropDownList1.Text);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
}
Regards
Open the connection while executing the command & not on page Load & wrap your code inside a try catch block to log the error.
protected void Button1_Click(object sender, EventArgs e)
{
SQLConnection cnn = new SqlConnection(WebConfigurationManager.ConnectionStrings["yourConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("insert into tbl_ragistration values(#f_name,#l_name,#email_id,#pass_word,#[date of brth],#add_ress,#gender)", cnn);
cmd.Parameters.AddWithValue("#f_name", Texfname.Text);
cmd.Parameters.AddWithValue("#l_name", Texlname.Text);
cmd.Parameters.AddWithValue("#email_id", Texemail.Text);
cmd.Parameters.AddWithValue("#pass_word", Texpwd.Text);
cmd.Parameters.AddWithValue("#[date o birth]", Texdbt.Text);
cmd.Parameters.AddWithValue("#add_ress", Texadd.Text);
cmd.Parameters.AddWithValue("#gender", DropDownList1.Text);
try
{
cnn.Open();
cmd.ExecuteNonQuery();
}
catch(SQLException ex)
{ // Log your error
lblStatus.Text="An error occured"+ ex.Message;
throw ex;
}
finally
{
if(cnn!=null)
{
cnn.Close();
}
}
}

Resources