im using the following code to populate a Gridview.I add 2 buttons for editing and deleting at the end.Hook to the click event.. but after i add the delete
button the click events are not firing.What im i doing wrong?
private void BindGrid2()
{
try
{
string constr = "Data Source=INSPIRE-1;" +
"Initial Catalog=testdatabase;" +
"User id=testuser;" +
"Password=tester;";
using (SqlConnection con = new SqlConnection(constr))
{
string commandText = "SELECT invnumber,itemname,quantity,rate FROM mytable2 where invnumber= #name";
using (SqlCommand command = new SqlCommand(commandText, con))
{
command.Parameters.AddWithValue("#name", text_inv.Text);
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView2.DataSource = dt;
}
}
}
if (flag2 == false)
{
flag2 = true;
DataGridViewButtonColumn uninstallButtonColumn = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "Edit";
uninstallButtonColumn.Text = "Edit";
dataGridView2.Columns.Insert(0, uninstallButtonColumn);
dataGridView2.Columns[0].DisplayIndex = 4;
DataGridViewButtonColumn uninstallButtonColumn2 = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "Delete";
uninstallButtonColumn.Text = "Delete";
dataGridView2.Columns.Insert(5, uninstallButtonColumn2);
dataGridView2.Columns[5].DisplayIndex = 5;
}
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
string orderId;
if (e.ColumnIndex == 4)
{
try
{
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value;
using (SqlConnection conn = new SqlConnection(constr))
{
try
{
conn.Open();
SqlDataReader myReader = null;
string commandText = "select * from mytable2 where invnumber= #name";
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.AddWithValue("#name", text_inv.Text);
myReader = command.ExecuteReader();
while (myReader.Read())
{
text_cname.Text = myReader["cname"].ToString();
text_quantity.Text = myReader["quantity"].ToString();
text_item.Text = myReader["itemname"].ToString();
text_rate.Text = myReader["rate"].ToString();
dateTimePicker1.Text = myReader["date"].ToString();
// textBox4.Text = myReader["stock"].ToString();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
catch (Exception error)
{
}
}
else if (e.ColumnIndex == 5)
{
using (SqlConnection conn = new SqlConnection(constr))
{
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value;
conn.Open();
SqlDataReader myReader = null;
string commandText = "delete from mytable2 where invnumber= #name";
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.AddWithValue("#name", text_inv.Text);
myReader = command.ExecuteReader();
}
BindGrid2();
}
}
Corrections below
dataGridView2.Columns.Insert(5, uninstallButtonColumn2) to dataGridView2.Columns.Insert(1, uninstallButtonColumn2)
if (e.ColumnIndex == 4) to if (e.ColumnIndex == 0)
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value; to orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[2].Value; at both the places
else if (e.ColumnIndex == 5) to else if (e.ColumnIndex == 1)
Related
I'm having a trouble with my code.
I'm trying to have the user the ability to submit his email to subscribe to my "notify me" service, I havn't code anything lately so I a bit confused..
I'm trying to Insert, Read, and Update data in my Online SQL Server.. but nothing seems to work! I don't know why I tried everything I know I check a million times it seems good.
Plus if there is any errors my catch should show it to me but even that doesn't work :(
Take a look at this maybe your eyes will see something I don't see.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["notifyCS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
try
{
string checkEmail = "SELECT User_Email FROM tbl_users WHERE User_Email = #User_Email";
string checkSubscription = "SELECT User_Status FROM tbl_users WHERE User_Email = #User_Email";
string submitEmail = "INSERT INTO tbl_users (User_UID, User_Email, User_Status) VALUES (#User_UID, #User_Email, #User_Status)";
string submitEmail2 = "UPDATE tbl_users SET User_UID = #User_UID, User_Status = #User_Status WHERE User_Email = #User_Email";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
SqlDataAdapter emailSDA = new SqlDataAdapter
{
SelectCommand = emailCMD
};
DataSet emailDS = new DataSet();
emailSDA.Fill(emailDS);
//if there is no email registered.
if (emailDS.Tables[0].Rows.Count == 0)
{
SqlCommand registerEmail = new SqlCommand(submitEmail, conn);
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail.ExecuteNonQuery();
registerEmail.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
else if (emailDS.Tables[0].Rows.Count > 0)
{
using (SqlCommand checkSub = new SqlCommand(checkSubscription, conn))
{
checkSub.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
SqlDataReader sdr = checkSub.ExecuteReader();
if (sdr.HasRows)
{
string res = sdr["User_Status"].ToString();
if (res != "subscribed")
{
using (SqlCommand registerEmail2 = new SqlCommand(submitEmail2, conn))
{
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail2.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail2.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail2.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail2.ExecuteNonQuery();
registerEmail2.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
}
else
{
conn.Close();
conn.Dispose();
Response.Redirect("index.aspx");
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
}
}
Try it this way:
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
string checkEmail = "SELECT * FROM tbl_users WHERE User_Email = #User";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
emailCMD.Parameters.Add("#User", SqlDbType.NVarChar).Value = email.Text;
SqlDataAdapter da = new SqlDataAdapter(emailCMD);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
DataTable emailRecs = new DataTable();
emailRecs.Load(emailCMD.ExecuteReader());
DataRow OneRec;
if (emailRecs.Rows.Count == 0)
{
OneRec = emailRecs.NewRow();
emailRecs.Rows.Add(OneRec);
}
else
{
// record exists
OneRec = emailRecs.Rows[0];
}
// modify reocrd
OneRec["User_UID"] = User_UID;
OneRec["User_Email"] = email.Text;
OneRec["User_Status"] = "subscribed";
email.Text = null;
da.Update(emailRecs);
}
}
I am 100% sure my listview has data. My program will get the ID from the column 0 of my listview, connects to the database, and using the ID as my reference will get the data from my database and display it to my textboxes/comboboxes. SO when I click an item from my listview, an exception appears and all of my textboxes as well as my comboboxes are empty. I am new to c# and programming, any help will be much appreciated.
using System;
using System.Data.OleDb;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
private string button = null;
private string carID;
public Form1()
{
InitializeComponent();
textDateReg.Text = DateTime.Now.ToString();
lvRefresh();
}
private void lvRefresh()
{
listView1.Items.Clear();
listView1.View = View.Details;
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\genesis\\Documents\\Database2.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand("Select ID, PlateNo from Cars", con);
OleDbDataReader cmdrdr = cmd.ExecuteReader();
if (cmdrdr.HasRows)
{
while (cmdrdr.Read())
{
ListViewItem list = new ListViewItem(cmdrdr["ID"].ToString());
list.SubItems.Add(cmdrdr["PlateNo"].ToString());
listView1.Items.Add(list);
}
}
con.Close();
cmdrdr.Close();
cmd.Dispose();
}
private void buttonNew_Click(object sender, EventArgs e)
{
button = "new";
buttonSub.Enabled = true;
panel1.Enabled = true;
}
private void textBox7_MouseClick(object sender, MouseEventArgs e)
{
textBox7.Text = null;
}
private void buttonSub_Click(object sender, EventArgs e)
{
switch (button)
{
case "new":
DialogResult dialogResult = MessageBox.Show("Are you sure you want to Register?", "Confirm", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
string Adrs = this.textADRS.Text;
string Fname = this.textFN.Text;
string Mname = this.textMN.Text;
string Lname = this.textLN.Text;
string Age = this.textAGE.Text;
string RegDate = this.textDateReg.Text;
string Gender = comboGender.SelectedItem.ToString();
string Phone = this.textPHONE.Text;
string Color = this.textColor.Text;
string Type = this.comboType.SelectedItem.ToString();
string Brand = this.textBrand.Text;
string Model = this.textModel.Text;
string PlateNo = this.textPlateNo.Text;
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\genesis\\Documents\\Database2.accdb";
OleDbCommand cmd = new OleDbCommand("Insert into Drivers (FirstName,MiddleName,LastName,Address,Age,PhoneNo,Gender,RegDate) Values (#FirstName,#MidName,#LastName,#Address,#Age,#Phone,#Gender,#RegDate)", con);
con.Open();
cmd.Parameters.Add(new OleDbParameter("#FirstName", Fname));
cmd.Parameters.Add(new OleDbParameter("#MidName", Mname));
cmd.Parameters.Add(new OleDbParameter("#LastName", Lname));
cmd.Parameters.Add(new OleDbParameter("#Address", Adrs));
cmd.Parameters.Add(new OleDbParameter("#Age", Age));
cmd.Parameters.Add(new OleDbParameter("#Phone", Phone));
cmd.Parameters.Add(new OleDbParameter("#Gender", Gender));
cmd.Parameters.Add(new OleDbParameter("#RegDate", RegDate));
cmd.ExecuteNonQuery();
cmd.Dispose();
cmd = new OleDbCommand("Insert into Cars(Color, Brand, Model, Type, PlateNo) Values(#Color, #Brand, #Model, #Type, #PlateNo)", con);
cmd.Parameters.Add(new OleDbParameter("#Color", Color));
cmd.Parameters.Add(new OleDbParameter("#Brand", Brand));
cmd.Parameters.Add(new OleDbParameter("#Model", Model));
cmd.Parameters.Add(new OleDbParameter("#Type", Type));
cmd.Parameters.Add(new OleDbParameter("#PlateNo", PlateNo));
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
MessageBox.Show("Record Submitted", "Nice!");
lvRefresh(); //refresh listview
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
break;
case "del":
dialogResult = MessageBox.Show("Are you sure you want to Register?", "Confirm", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
string Adrs = this.textADRS.Text;
string Fname = this.textFN.Text;
string Mname = this.textMN.Text;
string Lname = this.textLN.Text;
string Age = this.textAGE.Text;
string RegDate = this.textDateReg.Text;
string Gender = comboGender.SelectedItem.ToString();
string Phone = this.textPHONE.Text;
string Color = this.textColor.Text;
string Type = this.comboType.SelectedItem.ToString();
string Brand = this.textBrand.Text;
string Model = this.textModel.Text;
string PlateNo = this.textPlateNo.Text;
try
{
}
catch
{
}
}
break;
case "edit":
break;
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
panel1.Enabled = true;//panel that contains my textboxes/comboboxes
buttonDel.Enabled = true;
try
{
ListViewItem item = listView1.SelectedItems[0];
carID = item.Text;
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\genesis\\Documents\\Database2.accdb";
OleDbCommand cmd = new OleDbCommand("Select * from Drivers where ID = #ID", con);
con.Open();
cmd.Parameters.AddWithValue("#ID", carID);
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.HasRows)
{
textFN.Text = rdr["FirstName"].ToString();
textMN.Text = rdr["MiddleName"].ToString();
textLN.Text = rdr["LastName"].ToString();
textADRS.Text = rdr["Address"].ToString();
textPHONE.Text = rdr["PhoneNo"].ToString();
textDateReg.Text = rdr["RegDate"].ToString();
textAGE.Text = rdr["Age"].ToString();
comboGender.Text = rdr["Gender"].ToString();
if (!rdr.HasRows)
{
rdr.Close();
cmd.Dispose();
OleDbCommand cmdc = new OleDbCommand("Select * from Cars where ID = #ID", con);
cmdc.Parameters.AddWithValue("#ID", carID);
OleDbDataReader rdrc = cmdc.ExecuteReader();
while (rdrc.HasRows)
{
textColor.Text = rdr["Color"].ToString();
comboType.Text = rdr["Type"].ToString();
textBrand.Text = rdr["Brand"].ToString();
textModel.Text = rdr["Model"].ToString();
textPlateNo.Text = rdr["PlateNo"].ToString();
}
rdrc.Close();
cmdc.Dispose();
con.Close();
}
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
}
}
I am stuck at editing editing point after filtering the GridView By a drop down list(i.e dropdown is placed outside the gridview).
When I click on editlink after filtering the gridview it makes the starting rows of the whole grid editable.
I want to do this in ASP.NET instead of J-Query Or Ajax.!
Any One , Please Help me on this???
Here is my code:`
protected void FillGrid()
{
//String StudentSectionID = Convert.ToString(ddlsectionid.SelectedValue);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Final Year Project"].ToString());
con.Open();
string query = " SELECT St.StudentID, StudentNo, StudentPassword, StudentName, Cl.StudentClassName, Cl.StudentClassID,Se.StudentSectionID,Ge.StudentGenderID,Gu.StudentGuardianID,Tr.StudentTransportID,Se.StudentSectionName, StudentRollno, StudentSession, Ge.StudentGenderName, StudentPhone,StudentAddress, StudentEmail, Gu.StudentGuardianName, StudentReligion,Tr.StudentTransportRouteNo, StudentDOB,StudentFees from Student St Inner join Class Cl ON St.StudentClassID = Cl.StudentClassID Inner Join Section Se ON St.StudentSectionID = Se.StudentSectionID Inner Join Gender Ge ON Ge.StudentGenderID = St.StudentGenderID Inner Join Guardian Gu ON Gu.StudentGuardianID = St.StudentGuardianID Inner Join Transport Tr ON Tr.StudentTransportID = St.StudentTransportID";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gv_student.DataSource = ds;
gv_student.DataBind();
}
protected void ddlsectionid_SelectedIndexChanged(object sender, EventArgs e)
{
string StudentSectionName = Convert.ToString(ddlsectionid.SelectedItem);
SqlConnection oconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Final Year Project"].ToString());
oconn.Open();
SqlCommand ocmd = new SqlCommand("SELECT St.StudentID,StudentNo,StudentPassword, StudentName, Cl.StudentClassName, Se.StudentSectionName,Se.StudentSectionID, StudentRollno, StudentSession, Ge.StudentGenderName, StudentPhone, StudentAddress, StudentEmail, Gu.StudentGuardianName, StudentReligion, Tr.StudentTransportRouteNo, StudentDOB,StudentFees from Student St Inner join Class Cl ON St.StudentClassID = Cl.StudentClassID Inner Join Section Se ON St.StudentSectionID = Se.StudentSectionID Inner Join Gender Ge ON Ge.StudentGenderID = St.StudentGenderID Inner Join Guardian Gu ON Gu.StudentGuardianID = St.StudentGuardianID Inner Join Transport Tr ON Tr.StudentTransportID = St.StudentTransportID where Se.StudentSectionName='"+StudentSectionName+"'", oconn);
SqlDataAdapter oda = new SqlDataAdapter(ocmd);
SqlCommandBuilder builder = new SqlCommandBuilder(oda);
DataSet ds = new DataSet();
oda.Fill(ds);
gv_student.DataSource = ds;
gv_student.DataBind();
}
protected void gv_student_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlclassid = (DropDownList)e.Row.FindControl("ddlclassid");
DataTable dt;
string SQL = "SELECT * FROM Class";
string sConstr = ConfigurationManager.ConnectionStrings["Final Year Project"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr))
{
using (SqlCommand comm = new SqlCommand(SQL, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt = new DataTable("tbl");
da.Fill(dt);
}
}
}
ddlclassid.DataSource = dt;
ddlclassid.DataTextField = "StudentClassName";
ddlclassid.DataValueField = "StudentClassID";
ddlclassid.DataBind();
ddlclassid.SelectedValue = ((DataRowView)e.Row.DataItem)["StudentClassID"].ToString();
}
}
// For Section
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlsectionid = (DropDownList)e.Row.FindControl("ddlsectionid");
DataTable dt1;
string SQL1 = "SELECT * FROM Section";
string sConstr1 = ConfigurationManager.ConnectionStrings["Final Year Project"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr1))
{
using (SqlCommand comm = new SqlCommand(SQL1, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt1 = new DataTable("tbl");
da.Fill(dt1);
}
}
}
ddlsectionid.DataSource = dt1;
ddlsectionid.DataTextField = "StudentSectionName";
ddlsectionid.DataValueField = "StudentSectionID";
ddlsectionid.DataBind();
ddlsectionid.SelectedValue = ((DataRowView)e.Row.DataItem)["StudentSectionID"].ToString();
}
}
//For Gender
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlgenderid = (DropDownList)e.Row.FindControl("ddlgenderid");
DataTable dt2;
string SQL2 = "SELECT * FROM Gender";
string sConstr1 = ConfigurationManager.ConnectionStrings["Final Year Project"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr1))
{
using (SqlCommand comm = new SqlCommand(SQL2, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt2 = new DataTable("tbl");
da.Fill(dt2);
}
}
}
ddlgenderid.DataSource = dt2;
ddlgenderid.DataTextField = "StudentGenderName";
ddlgenderid.DataValueField = "StudentGenderID";
ddlgenderid.DataBind();
ddlgenderid.SelectedValue = ((DataRowView)e.Row.DataItem)["StudentGenderID"].ToString();
}
}
//For Guardian
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlguardianid = (DropDownList)e.Row.FindControl("ddlguardianid");
DataTable dt3;
string SQL3 = "SELECT * FROM Guardian";
string sConstr1 = ConfigurationManager.ConnectionStrings["Final Year Project"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr1))
{
using (SqlCommand comm = new SqlCommand(SQL3, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt3 = new DataTable("tbl");
da.Fill(dt3);
}
}
}
ddlguardianid.DataSource = dt3;
ddlguardianid.DataTextField = "StudentGuardianName";
ddlguardianid.DataValueField = "StudentGuardianID";
ddlguardianid.DataBind();
ddlguardianid.SelectedValue = ((DataRowView)e.Row.DataItem)["StudentGuardianID"].ToString();
}
}
//For Transport
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddltransportid = (DropDownList)e.Row.FindControl("ddltransportid");
DataTable dt4;
string SQL4 = "SELECT * FROM Transport";
string sConstr1 = ConfigurationManager.ConnectionStrings["Final Year Project"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr1))
{
using (SqlCommand comm = new SqlCommand(SQL4, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt4 = new DataTable("tbl");
da.Fill(dt4);
}
}
}
ddltransportid.DataSource = dt4;
ddltransportid.DataTextField = "StudentTransportRouteNo";
ddltransportid.DataValueField = "StudentTransportID";
ddltransportid.DataBind();
ddltransportid.SelectedValue = ((DataRowView)e.Row.DataItem)["StudentTransportID"].ToString();
}
}
}
protected void gv_student_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int StudentID = Convert.ToInt32(gv_student.DataKeys[e.RowIndex].Value);
SqlConnection oconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Final Year Project"].ToString());
oconn.Open();
SqlCommand ocmd = new SqlCommand();
ocmd.CommandText = "DELETE FROM Student WHERE StudentID=#StudentID";
ocmd.Parameters.AddWithValue("#StudentID", StudentID);
ocmd.Connection = oconn;
ocmd.ExecuteNonQuery();
oconn.Close();
FillGrid();
}
protected void gv_student_RowEditing(object sender, GridViewEditEventArgs e)
{
gv_student.EditIndex = e.NewEditIndex;
FillGrid();
}
protected void gv_student_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int StudentID = int.Parse(((Label)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("lbl_ID"))).Text);
string StudentNo = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtno"))).Text;
string StudentPassword = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtpassword"))).Text;
string StudentName = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtname"))).Text;
string StudentRollno = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtrollno"))).Text;
string StudentSession = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtsession"))).Text;
string StudentPhone = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtphone"))).Text;
string StudentAddress = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtaddress"))).Text;
string StudentEmail = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtemail"))).Text;
string StudentReligion = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtreligion"))).Text;
string StudentDOB = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtdob"))).Text;
string StudentFees = ((TextBox)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("txtfees"))).Text;
int StudentClassID = int.Parse(((DropDownList)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("ddlclassid"))).SelectedValue);
int StudentSectionID = int.Parse(((DropDownList)(gv_student.Rows[e.RowIndex].FindControl("ddlsectionid"))).SelectedValue);
int StudentGenderID = int.Parse(((DropDownList)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("ddlgenderid"))).SelectedValue);
int StudentGuardianID = int.Parse(((DropDownList)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("ddlguardianid"))).SelectedValue);
int StudentTransportID = int.Parse(((DropDownList)(gv_student.Rows[e.RowIndex].Cells[1].FindControl("ddltransportid"))).SelectedValue);
SqlConnection oconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Final Year Project"].ToString());
oconn.Open();
SqlCommand ocmd = new SqlCommand();
ocmd.CommandText = "UPDATE Student SET StudentNo=#StudentNo, StudentPassword=#StudentPassword, StudentName=#StudentName,StudentRollno=#StudentRollno,StudentSession=#StudentSession,StudentPhone=#StudentPhone,StudentAddress=#StudentAddress,StudentEmail=#StudentEmail,StudentReligion=#StudentReligion,StudentDOB=#StudentDOB,StudentFees=#StudentFees,StudentTransportID=#StudentTransportID,StudentGuardianID=#StudentGuardianID,StudentGenderID=#StudentGenderID,StudentSectionID=#StudentSectionID,StudentClassID=#StudentClassID WHERE StudentID=#StudentID";
ocmd.Parameters.AddWithValue("#StudentID", StudentID);
ocmd.Parameters.AddWithValue("#StudentClassID", StudentClassID);
ocmd.Parameters.AddWithValue("#StudentSectionID", StudentSectionID);
ocmd.Parameters.AddWithValue("#StudentGenderID", StudentGenderID);
ocmd.Parameters.AddWithValue("#StudentGuardianID", StudentGuardianID);
ocmd.Parameters.AddWithValue("#StudentTransportID", StudentTransportID);
ocmd.Parameters.AddWithValue("#StudentFees", StudentFees);
ocmd.Parameters.AddWithValue("#StudentDOB", StudentDOB);
ocmd.Parameters.AddWithValue("#StudentReligion", StudentReligion);
ocmd.Parameters.AddWithValue("#StudentEmail", StudentEmail);
ocmd.Parameters.AddWithValue("#StudentAddress", StudentAddress);
ocmd.Parameters.AddWithValue("#StudentPhone", StudentPhone);
ocmd.Parameters.AddWithValue("#StudentSession", StudentSession);
ocmd.Parameters.AddWithValue("#StudentRollno", StudentRollno);
ocmd.Parameters.AddWithValue("#StudentName", StudentName);
ocmd.Parameters.AddWithValue("#StudentPassword", StudentPassword);
ocmd.Parameters.AddWithValue("#StudentNo", StudentNo);
ocmd.Connection = oconn;
ocmd.ExecuteNonQuery();
gv_student.EditIndex = -1;
FillGrid();
oconn.Close();
}
protected void gv_student_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gv_student.EditIndex = -1;
FillGrid();
}
I wanted to update my database that contains two text and one filename that is needed for image.
The problem is that the image and filename updates but the two other text values title and body wont be affected and don't change the previous values. Also visual studio don't get any problem and the message for executing command shows that it's executed the command but nothing except the image changes.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
Response.Redirect("~/default.aspx");
if (Request .QueryString ["action"]=="edit")
{
Panel1.Visible = true;
}
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString =GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString () + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text=myReader ["Title"].ToString ();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
protected void btn_addpost_Click(object sender, EventArgs e)
{
string title= title_txt .Text ;
string body=bodytxt .Text ;
if (Request.QueryString["edit"] != null)
{
string message;
string filename = thumb_uploader.FileName;
string path = HttpContext.Current.Server.MapPath("~") + "\\Thumb";
string exup = System.IO.Path.GetExtension(thumb_uploader.FileName);
string[] ext = { ".jpg", ".png", ".jpeg" };
if (Array.IndexOf(ext, exup) < 0)
{
message = "not correct.";
}
if (thumb_uploader.FileBytes.Length / 1024 > 400)
{
message = "not currect.";
}
while (System.IO.File.Exists(path + "\\" + filename + exup))
{
filename += "1";
}
savepath = path + "\\" + filename;
if (thumb_uploader.HasFile)
{
thumb_uploader.SaveAs(savepath);
thumb = thumb_uploader.FileName;
SqlCommand command;
SqlDataAdapter da;
SqlConnection con3 = new SqlConnection();
con3.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
command = new SqlCommand();
command.Connection = con3;
da = new SqlDataAdapter();
da.SelectCommand = command;
command.CommandText = "UPDATE tbl_post SET Title=#title ,Body=#body ,Thumb=#thu Where Postid=" + Request.QueryString["edit"].ToString();
con3.Open();
command.Parameters.AddWithValue("#title", title );
command.Parameters.AddWithValue("#body", body );
command.Parameters.AddWithValue("#thu", thumb_uploader .FileName);
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
else
{
using (SqlConnection con3 = new SqlConnection(GNews.Properties.Settings.Default.connectionstring))
{
string sql = "update tbl_post SET Title=#title ,Body=#body Where Postid=#postid" ;
using (SqlCommand command = new SqlCommand(sql, con3))
{
con3.Open();
command.Parameters.AddWithValue("#title", title);
command.Parameters.AddWithValue("#body", body);
command.Parameters.AddWithValue("#postid", Request.QueryString["edit"].ToString());
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
}
}
}
I've found the answer I needed this code to include my pageload reading database so it wouldn't do it when I click on the update button.I mean the problem was all about the post back thing.
if (!Page.IsPostBack)
{
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString() + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text = myReader["Title"].ToString();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
}
I have a windows form of controls combobox and datetimepicker..
I have given null or empty to combobox in page load..
so combobox shows empty intially while loading database values to it in windows form..
but the problem is
because of the datetimepicker is not kept to null or empty my form is showing message box as "the day is already existed" before form is desplaying..here my code follows
I want to show that message after combobox value is selected..
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name from Employee_Details", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("employee_id", typeof(string));
dt.Columns.Add("employee_name", typeof(string));
dt.Load(dtr);
comboBox1.DisplayMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = null;
if(comboBox1.SelectedItem == null)
{
txtemployeeid.Text = "";
txtemployeename.Text = "";
}
cn.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("select employee_id,Employee_name from Employee_Details where employee_name=('" + comboBox1.Text + "')", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
if (dtr.Read())
{
string employee_id = (string)dtr["employee_id"];
string employee_name = (string)dtr["employee_name"];
txtemployeeid.Text = employee_id;
txtemployeename.Text = employee_name;
dtr.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
if (comboBox1.SelectedItem != null)
{
try
{
string dtp = dateTimePicker1.Value.ToString("dd/MM/yyyy");
SqlCommand cmd1 = new SqlCommand("select date from dailyattendance where date=('" + dtp + "') and employee_id='" + txtemployeeid.Text + "' and empployee_name='" + txtemployeename.Text + "' ", cn);
SqlDataReader dtr1;
dtr1 = cmd1.ExecuteReader();
if (dtr1.Read())
{
string date = (string)dtr1["date"];
if (dtp == date)
{
MessageBox.Show("this day is already existed");
}
}
dtr1.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
}
cn.Close();
}
can any one solve it please..Thanx in advance
You can simply use dtr.Text="";