in this code error is showing "Type or namespace definantion,end of file expected" - asp.net

Type or namespace definantion,end of file expected
public partial class contact : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
if (TextBox1.Text == "")
{
/* Label2.Text = "name is compulasry";*/
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('name is compulasry');", true);
}
else
{
SqlConnection con = new SqlConnection(#"Data Source=SYSTEM2\SQLEXPRESS;Initial Catalog=amresh;Integrated Security=True");
SqlCommand cmd;
con.Open();
cmd = new SqlCommand("insert into Deatil values('"+ TextBox1.Text +"')", con);
cmd.ExecuteNonQuery();
ClearInputs(Page.Controls);
con.Close();
}
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
ClearInputs(ctrl.Controls);
}
}
}
}

You missed to close Button1_Click1. You're missing a }
protected void Button1_Click1(object sender, EventArgs e)
{
if (TextBox1.Text == "")
{
/* Label2.Text = "name is compulasry";*/
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('name is compulasry');", true);
}
else
{
SqlConnection con = new SqlConnection(#"Data Source=SYSTEM2\SQLEXPRESS;Initial Catalog=amresh;Integrated Security=True");
SqlCommand cmd;
con.Open();
cmd = new SqlCommand("insert into Deatil values('"+ TextBox1.Text +"')", con);
cmd.ExecuteNonQuery();
ClearInputs(Page.Controls);
con.Close();
}
} // <-- This is missed
And you need to remove an extra } at the end
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
ClearInputs(ctrl.Controls);
}
}
} // <-- Remove this

Related

System.ArgumentOutOfRangeException When Handling Button Click

I used a button field in a gridview. When I press button, which has index greater than 5, I received this exception:
System.ArgumentOutOfRangeException: 'Index was out of range. Must be
non-negative and less than the size of the collection.'
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "btn")
{
int crow;
crow = Convert.ToInt32(e.CommandArgument.ToString());
string v = GridView1.Rows[crow].Cells[1].Text;
int a = Int32.Parse(v);
string b = "true";
SqlConnection con = new SqlConnection("Data Source=DESKTOP-LITEG8T;Initial Catalog=UserDb;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE Table_1 SET Status ='"+b+"' WHERE Id ='"+ a+"'", con);
cmd.ExecuteNonQuery();
con.Close();
v = "";
}
}
}
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "btn")
{
int crow;
crow = Convert.ToInt32(e.CommandArgument.ToString());
try
{
string v = GridView1.Rows[crow].Cells[1].Text;
Application["id"] = v;
v = "";
}
catch (ArgumentOutOfRangeException)
{
}
finally
{
string a = Application["id"].ToString();
Label1.Text = a.ToString();
string b = "true";
SqlConnection con = new SqlConnection("Data Source=DESKTOP-LITEG8T;Initial Catalog=UserDb;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE Table_1 SET Status ='" + b + "' WHERE Id ='" + a + "'", con);
cmd.ExecuteNonQuery();
con.Close();
Application["id"] = "";
a = "";
}
}
}
}

Gridview doesn't refresh after deleting a row

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.

Grid View only updates when page refresh

In my application i have a grid view and a save task button. when i click save task my button , the Grid View doesn't refresh but when i click the refresh button of browser the grid refreshes and automatically add another task in the database. All i want is to refresh the grid when save task button is click and not add task when browser refresh button is clicked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
static string startdate;
DataTable dt;
static string enddate;
static string EstDate;
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
protected void Page_Load(object sender, EventArgs e)
{//Page dosn't go back//
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetNoStore();
if (IsPostBack)
{
if (Session["auth"] != "ok" )
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
//Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
else
{
GridView1.DataSource = dt;
GridView1.DataBind();
if (Session["auth"] != "ok")
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
// Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
//decode url data in query string
labelID.Text = HttpUtility.UrlDecode(Request.QueryString["Id"]);
labelDur.Text = HttpUtility.UrlDecode(Request.QueryString["Duration"]);
labelStatus.Text = HttpUtility.UrlDecode(Request.QueryString["Status"]);
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
if (!IsPostBack)
{
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
}
protected void saveTask_Click(object sender, EventArgs e)
{
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
try
{
String query = "insert into Tasks (T_Description, T_Status,S_ID,StartDate,EstEndDate) values('" + TaskDesBox.Text + "', 'incomplete','" + labelID.Text + "' ,'" + startdate + "','" + EstDate + "');";
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
GridView1.DataBind();
}
else
{
TaskStatus.Text = "Task not Saved";
}
}
catch (Exception ex)
{
Response.Write("reeor" + ex);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void TaskDesBox_TextChanged(object sender, EventArgs e)
{
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
startdate = Calendar1.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
SDate.Text = startdate;
Calendar1.Visible = false;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Calendar2.Visible = true;
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
EstDate = Calendar2.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
EstDateBox.Text = EstDate;
Calendar2.Visible = false;
}
}
What you are doing on a post back is:
First show the results due to code in your Page_Load
Then perform event handlers, so if you pushed the Save button, the saveTask_Click will be performed, which adds a record to the database. You don't update your grid view datasource, but just call DataBind() afterwards which still binds the original DataSource.
Imo you shouldn't update your grid view on Page_Load. You should only show it initially on the GET (!IsPostBack).
And at the end of saveTask_Click you have to update your grid view again.
So move the code you need to show the grid view to a method you can call on other occasions:
protected void ShowGridView() {
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Then call it in your Page_Load on !IsPostBack
if (!IsPostBack)
{
ShowGridView();
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
Then after adding the row in saveTask_Click you can call ShowGridView() to see the new result.
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
//GridView1.DataBind();
ShowGridView();
}
else
{
TaskStatus.Text = "Task not Saved";
}

dropdownlist index changed value

I have a problem when I change dropdownlist1 item, The changed item not being accessed on the event of DropDownList1_SelectedIndexChanged.
Here is my code...
namespace My_News.Views.Shared
{
public partial class Master : System.Web.UI.MasterPage
{
SqlDataReader dr;
string user_id = "";
protected void Page_Load(object sender, EventArgs e)
{
/* user login information */
if (Session["status"] != null)
{
Button1.Text = "Logout";
Button2.Visible = true; ;
Button2.Text = Session["name"] as string + "'s Profile";
Button3.Enabled = true;
DropDownList1.Enabled = true;
user_id = Session["reg_id"] as string;
DropDownList1.Items.Clear();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection_String"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT DISTINCT[news_category] from [news_profile] WHERE [user_id]='" + user_id + "'";
cmd.Connection = connection;
connection.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
connection.Close();
}
}
}
else
{
Button1.Text = "Login";
Button2.Visible = false;
Button3.Enabled = false;
DropDownList1.Enabled = false;
Session.Clear();
}
}
Dropdownnlist index change event...
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["news_category"] = DropDownList1.Text;
Session["reload"] = "yes";
Session.Timeout = 10;
Response.Redirect("Default.aspx");
}
}
}
Please help me.
You need to modify your code like this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindDDL();
}
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
string s = ddl.Text;
}
public void bindDDL()
{
DataTable dt = new DataTable("Drop");
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "ABCD");
dt.Rows.Add(2, "EFGH");
ddl.DataSource = dt;
ddl.DataValueField = "ID";
ddl.DataTextField = "Name";
ddl.DataBind();
}

radio button not working in asp.net

I am beginner.radio button not working properly. I dn't know what is a problem
protected void RadioButton1_CheckedChanged1(object sender, EventArgs e)
{
if (RadioButton1.Checked == true)
{
Label1.Text = "Upload our video file";
RadioButton2.Checked = false;
}
else
{
Label1.Text = "Upload our image file";
RadioButton1.Checked = false;
}
}
public void upload()
{
SqlCommand cmd = new SqlCommand("insert into video_info(Name,path,user_name,email,comment)values(#Name,#path,#user_name,#email,#comment)", con);
cmd.Parameters.AddWithValue("#Name", txt_file.Text);
cmd.Parameters.AddWithValue("#path", "video/" + fileuplod.FileName);
cmd.Parameters.AddWithValue("#user_name", use_name.Text);
cmd.Parameters.AddWithValue("#email", email.Text);
cmd.Parameters.AddWithValue("#comment", comment.Text);
fileuplod.SaveAs(Server.MapPath("~/video/" + fileuplod.FileName));
cmd.ExecuteNonQuery();
}
protected void submit_Click(object sender, EventArgs e)
{
upload();
}
}
What I want to do.I have two radio button.Image and video.Suppose user select image.then all the detail will save on image table or if user click on video.All the detail goes to image_database.
May be my logic is wrong.
put auto postback to true in radiobutton property
Try this
public void upload(string query)
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Name", txt_file.Text);
cmd.Parameters.AddWithValue("#path", "video/" + fileuplod.FileName);
cmd.Parameters.AddWithValue("#user_name", use_name.Text);
cmd.Parameters.AddWithValue("#email", email.Text);
cmd.Parameters.AddWithValue("#comment", comment.Text);
fileuplod.SaveAs(Server.MapPath("~/video/" + fileuplod.FileName));
cmd.ExecuteNonQuery();
}
protected void submit_Click(object sender, EventArgs e)
{
string query;
if (RadioButton1.Checked == true)
{
query="insert into video_info(Name,path,user_name,email,comment)values(#Name,#path,#user_name,#email,#comment)";
Label1.Text = "Upload our video file";
RadioButton2.Checked = false;
}
else
{
query="insert into Image_info(Name,path,user_name,email,comment)values(#Name,#path,#user_name,#email,#comment)";
Label1.Text = "Upload our image file";
RadioButton1.Checked = false;
}
if(query!="")
{
upload(query);
}
}

Resources