update button on nested gridview asp.net c# - c#

I have this nested grid view in which the data are shown in textboxes and i also have an update button but when i click the button instead of updating the data on the data table it just updates the new value on the grid view itself and shows it along with the old value and i don't get any error though. Please help me thanks.
the code:
private static DataTable GetData(string query)
{
string strConnString = ConfigurationManager.ConnectionStrings["MandapamDatabase"].ConnectionString;
using (OleDbConnection con = new OleDbConnection(strConnString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandText = query;
using (OleDbDataAdapter sda = new OleDbDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ID = gvSDate.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvSDate2 = e.Row.FindControl("gvSDate2") as GridView;
gvSDate2.DataSource = GetData(string.Format("select ID, Function, FunctionDate, FunctionTime, CelebrateName from function where ID={0}", ID));
gvSDate2.DataBind();
}
}
protected void gvSDate2_RowDataBound(object sender, GridViewRowEventArgs f)
{
if (f.Row.RowType == DataControlRowType.DataRow)
{
GridView gvSDate2 = f.Row.FindControl("gvSDate2") as GridView;
TextBox textFunction = f.Row.FindControl("textFunction") as TextBox;
TextBox textFunctionDate = f.Row.FindControl("textFunctionDate") as TextBox;
TextBox textFunctionTime = f.Row.FindControl("textFunctionTime") as TextBox;
TextBox textCelebrateName = f.Row.FindControl("textCelebrateName") as TextBox;
Label lblID = f.Row.FindControl("lblID") as Label;
Button update1 = f.Row.FindControl("update1") as Button;
string Function = textFunction.Text;
string FunctionDate = textFunctionDate.Text;
string FunctionTime = textFunctionTime.Text;
string CelebrateName = textCelebrateName.Text;
string ID1 = lblID.Text;
update1.Click += (send, g) =>
{
string connString = ConfigurationManager.ConnectionStrings["MandapamDatabase"].ConnectionString;
OleDbConnection connection = new OleDbConnection(connString);
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string updateQuery = "UPDATE function SET Function=#Function, FunctionDate=#FunctionDate, FunctionTime=#FunctionTime, CelebrateName=#CelebrateName WHERE ID=#ID";
command.CommandType = CommandType.Text;
command.CommandText = updateQuery;
command.Parameters.AddWithValue("#ID", ID1);
command.Parameters.AddWithValue("#Function", Function);
command.Parameters.AddWithValue("#FunctionDate", FunctionDate);
command.Parameters.AddWithValue("#FunctionTime", FunctionTime);
command.Parameters.AddWithValue("#CelebrateName", CelebrateName);
};
}
}

Related

Asp.Net finding in Code-behind edited values in GridView with autogenerated columns

I am trying to create a user control of a gridview that will be able to display, edit and delete records, being bound to any datatable.
In my user control I have:
<asp:GridView ID="EditableGrid" runat="server" Width="500px" Height="500px" AllowSorting="True"
AutoGenerateColumns = "true"
AutoGenerateDeleteButton ="true" AutoGenerateEditButton="true"
OnRowEditing="EditableGrid_RowEditing"
OnRowCancelingEdit="EditableGrid_RowCancelingEdit"
OnRowUpdating="EditableGrid_RowUpdating"
OnRowDeleting="EditableGrid_RowDeleting"
></asp:GridView>
In my code behind I have:
public void InitGrid(string theconnstr, string thetablename)
{
connstr = theconnstr;
tablename = thetablename;
// Session["edgconnstr"] = connstr;
// Session["edgtablename"] = tablename;
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (!rd.HasRows) return;
fields = new List<EdField>();
for (int i =0; i < rd.FieldCount; i++)
{
fields.Add(new EdField(rd.GetName(i), rd.GetDataTypeName(i)));
}
}
}
con.Close();
}
public void Bind()
{
// connstr = (String)Session["edgconnstr"];
// tablename = (String)Session["edgtablename"];
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
EditableGrid.DataSource = dt;
EditableGrid.DataBind();
EditableGrid.Visible = true;
}
}
}
con.Close();
}
protected void EditableGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
EditableGrid.EditIndex = e.NewEditIndex;
Bind();
}
protected void EditableGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
EditableGrid.EditIndex = -1;
Bind();
}
protected void EditableGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
Now I have tried with no success to find the new values of the edited row in the EditableGrid_RowUpdating event handler. I just do not have access to the textboxes, and therefore I cannot run the query to update the old values to the new value. Is what I want to achieve even possible?
Use the e.NewValues Collection.
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int tx = Convert.ToInt32(e.NewValues[0]);
}

How to enable all textbox controls in itemtemplate of Repeater by itemCommand?

I have a repeater and I used label for display and a hidden text box which holds the same value. Now I want to enable the text box so that the user can edit inputs in the table/repeater. Can anyone help me? below is my code
public void FillTable()
{
DataTable table = new DataTable();
using (MySqlConnection conn = Functions.GetConnection())
{
string sql = "SELECT FirstName, LastName from tbluser LIMIT 15";
using (MySqlCommand cmd = new MySqlCommand(sql, conn))
{
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(table);
conn.Close();
}
}
asd.DataSource = table;
asd.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
asd.Visible = true;
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
RepeaterItem item = e.Item;
Literal lblname = (Literal)item.FindControl("Label2");
TextBox txtbox = (TextBox)item.FindControl("Label3");
if (e.CommandName == "EDIT")
{
lblname.Visible = false;
txtbox.Visible = true;
You are not getting the textbox but the label twice:
TextBox txtbox = (TextBox)item.FindControl("Label3");

Dynamically Binded Dropdownlist always taking first value when get by ddl.SelectedValue

I have a dynamically bind dropdownlist from which i want insert selected value in a table. But when I submit the form it is taking the very first value of dropdownlist not the selected value and inserts the first value of the dropdownlist.
Here is my code
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlGetClass = "select pk_classID,brachName+'-'+classYear as classInfo from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "classInfo";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
}
}
protected void btnStdRegisterSubmit_Click(object sender, EventArgs e)
{
string dateOfBirth = txtStdDOBYear.Text+"-"+ddlStdDOBMonth.SelectedValue + "-"+txtStdDOBDate.Text;
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlInsertStd = "Insert into tbl_studentRegistration (firstName,surname,studentUsername,studentPassword,studentDOB,studentGender,studentMobile,class) values(#firstName,#surname,#studentUsername,#studentPassword,#studentDOB,#studentGender,#studentMobile,#class)";
conn.Open();
SqlCommand cmdInsertStd = new SqlCommand(sqlInsertStd, conn);
cmdInsertStd.Parameters.AddWithValue("#firstName", txtStdFirstName.Text);
cmdInsertStd.Parameters.AddWithValue("#surname", txtStdSurname.Text);
cmdInsertStd.Parameters.AddWithValue("#studentUsername", txtStdUsername.Text);
cmdInsertStd.Parameters.AddWithValue("#studentPassword", txtStdPassword.Text);
cmdInsertStd.Parameters.AddWithValue("#studentDOB", DateTime.Parse(dateOfBirth).ToString("yyyy-MM-dd"));
cmdInsertStd.Parameters.AddWithValue("#studentGender", ddlStdGender.SelectedValue.ToString());
cmdInsertStd.Parameters.AddWithValue("#studentMobile", txtStdMobile.Text);
cmdInsertStd.Parameters.AddWithValue("#class", ddlClass.SelectedValue);
cmdInsertStd.ExecuteNonQuery();
conn.Close();
txtStdFirstName.Text = "";
txtStdSurname.Text = "";
txtStdUsername.Text = "";
ddlClass.SelectedValue = "";
txtStdPassword.Text = "";
txtStdConfirmPassword.Text = "";
ddlStdDOBMonth.SelectedValue = "";
txtStdDOBDate.Text = "";
txtStdDOBYear.Text = "";
ddlStdGender.SelectedValue = "";
txtStdMobile.Text = "";
Response.Redirect("~/index.aspx");
}
}
Please help I am new to asp.net
Problem : You are adding the items into DropDownList for every Page request as your code added in Page_Load EventHandler. so the DropDownList always contain the first item as selectedItem even though you selected different item.
Solution: You need to append the items into DropDownList only when page is Loaded but not on every PostBack request.
You can use Page.IsPostBack to identify wether page request is PostBack request or not.
Try This:
if(!Page.IsPostBack)
{
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlGetClass = "select pk_classID,brachName+'-'+classYear as
classInfo from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "classInfo";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
}
}
Page_Load executes every time the page posts back, such as when you click your submit button. You should put your using stateme3nt in a
conditional:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlGetClass = "select pk_classID,brachName+'-'+classYear as classInfo from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "classInfo";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
}
}
}
So that your list is not repopulated every time you click your submiit button.
(you should consider putting the list population code in a separate method)

How to bind a drop-down control to a data source in ASP.NET

I am new to C#.
I have a project to create an HR system and I created a page to add employees but the supervisor asked me to create a drop down list that displays the department when adding a new employee.
I don't know how to start and what I should do first. I already added a drop down list from the tools but I don't know how to choose the data source and the name and value of it. Should I choose the department table or the employee table?
public partial class _Default : Page
{
private String strcon = ConfigurationManager.ConnectionStrings["hr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
bindgrideview();
}
protected void bindgrideview()
{
SqlConnection strcon1 = new SqlConnection(strcon);
strcon1.Open();
string ADDStr = "SELECT F_name , L_name , salary FROM Employee ";
SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(ADDCmd);
adapter.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
string F_name = TextBox1.Text;
string L_name = TextBox2.Text;
int status = 1;
string salarystr = TextBox3.Text.ToString();
int salary = Int32.Parse(salarystr);
SqlConnection strcon1 = new SqlConnection(strcon);
strcon1.Open();
string ADDStr = "ADDEMP";
SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
ADDCmd.CommandType = CommandType.StoredProcedure;
ADDCmd.Parameters.AddWithValue("#F_name", F_name);
ADDCmd.Parameters.AddWithValue("#L_name", L_name);
ADDCmd.Parameters.AddWithValue("#status", status);
ADDCmd.Parameters.AddWithValue("#salary", salary);
ADDCmd.ExecuteNonQuery();
bindgrideview();
TextBox1.Text = "";
TextBox2.Text = "";
}
And this is a screen shot of my page:
http://store2.up-00.com/Nov12/YXb11858.png
this is the final code there is no error but the dropdown list have no item :(
public partial class _Default : Page
{
private String strcon = ConfigurationManager.ConnectionStrings["hr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
bindgrideview();
}
protected void bindgrideview()
{
SqlConnection strcon1 = new SqlConnection(strcon);
strcon1.Open();
string ADDStr = "SELECT F_name , L_name , salary FROM Employee ";
SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(ADDCmd);
adapter.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
string F_name = TextBox1.Text;
string L_name = TextBox2.Text;
int status = 1;
string salarystr = TextBox3.Text.ToString();
int salary = Int32.Parse(salarystr);
SqlConnection strcon1 = new SqlConnection(strcon);
strcon1.Open();
string ADDStr = "ADDEMP";
SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
ADDCmd.CommandType = CommandType.StoredProcedure;
ADDCmd.Parameters.AddWithValue("#F_name", F_name);
ADDCmd.Parameters.AddWithValue("#L_name", L_name);
ADDCmd.Parameters.AddWithValue("#status", status);
ADDCmd.Parameters.AddWithValue("#salary", salary);
ADDCmd.ExecuteNonQuery();
bindgrideview();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
}
protected void bindDepartments()
{
SqlConnection strcon1 = new SqlConnection(strcon);
strcon1.Open();
string ADDStr = "SELECT ID,department_name FROM Department ";
SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(ADDCmd);
adapter.Fill(table);
DropDownList1.DataSource = table;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "department_name";
DropDownList1.DataBind();
}
}
As your code works for retrieving Employees Info. from database, you will retrieve the Departments info. from your Departments table.
protected void bindDepartments()
{
SqlConnection strcon1 = new SqlConnection(strcon);
strcon1.Open();
string ADDStr = "SELECT DepartmentId,DepartmentName FROM Departments ";
SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(ADDCmd);
adapter.Fill(table);
ddlDepartments.DataSource = table;
ddlDepartments.DataValueField = "DepartmentId"; //The Value of the DropDownList, to get it you should call ddlDepartments.SelectedValue;
ddlDepartments.DataTextField = "DepartmentName"; //The Name shown of the DropDownList.
ddlDepartments.DataBind();
}

error in finding control in gridview

I had gridview which on databound I need to hid Image control so I did this code but error apear( grid view dosenot containe defination of RowIndex) when i tried to find control
C# Code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Img = GridView1.Rows[e.RowIndex].FindControl("Logo") as Image ;
using (SqlConnection con = Connection.GetConnection())
{
string Sql = "Select Logo From Model where Id=#Id";
SqlCommand com = new SqlCommand(Sql, con);
com.Parameters.Add(Parameter.NewInt("#Id", DDLModel.SelectedValue));
com.CommandType = CommandType.Text;
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
string Img2 = dr["Logo"].ToString();
if (Img2 == System.DBNull.Value.ToString())
{
Img.Visible = false;
}
}
}
}
GridViewRowEventArgs contains the row so you could try:
image = e.Row.FindControl("Logo") as Image;

Categories