I am using window.open to open 2 different pages in pop-up windows,but for some reason both the triggers opens the same page in the pop-up window,heres how I am trying to do this:
first:
Response.Write("<script type='text/javascript'>window.open('TransEditEntry.aspx','mywindow','width=850px,height=300px,left=0,top=10,screenX=100,screenY=10')</script>");
second:
Response.Write(#"<script type='text/javascript'>window.open('TransNewEntry.aspx','','width=850px,height=300px,left=0,top=10,screenX=100,screenY=10')</script>");
this opens 'TransEditEntry.aspx' page instead of 'TransNewEntry.aspx'`
here the rest of the code:
The entire function which is called on add button click:
protected void addNew(object sender, EventArgs e)
{
//HiddenField sr = (HiddenField)GridView1.SelectedRow.Cells[6].FindControl("srno");
//Session["TransSrNo"] = sr.Value;
Response.Write(#"<script type='text/javascript'>window.open('TransNewEntry.aspx','','width=850px,height=300px,left=0,top=10,screenX=100,screenY=10')</script>");
//Session["transAdd"] = "1";
}
The add button which calls the function:
<asp:Button ID="AddBtn" runat="server" OnClick="addNew" Text="Add"/>
The page TransNewEntry.aspx.cs
public partial class TransEditEntry : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(GetConnectionString.Get());
string subCode;
DataTable dt;
SqlDataAdapter sda;
SqlCommandBuilder build;
DataRow dr;
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
Response.Write((Session["TransSrNo"]).ToString());
int SRno = Convert.ToInt32((Session["TransSrNo"]).ToString());
con.Open();
SqlCommand cmd3 = new SqlCommand("select sub_code from tran_dtls where sr_no='" + SRno + "'", con);
subCode = (string)cmd3.ExecuteScalar();
con.Close();
if (!IsPostBack)
{
sda = new SqlDataAdapter("select * from tran_dtls where sr_no=" + SRno + "", con);
build = new SqlCommandBuilder(sda);
dt = new DataTable();
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
srNoTxt.Text = "";
amttxt.Text = "";
partTxt.Text = "";
checkNoTxt.Text = "";
checkDtTxt.Text = "";
refNoTxt.Text = "";
refDtTxt.Text = "";
jobNoTxt.Text = "";
}
}
}
protected void GlChange(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd4 = new SqlCommand("select ac_type from ac_mstr where AC_desc='" + GlDrp.SelectedValue + "'", con);
string acType = (string)cmd4.ExecuteScalar();
SqlCommand cmd5 = new SqlCommand("select gl_code from ac_mstr where AC_desc='" + GlDrp.SelectedValue + "'", con);
string gl_code = (string)cmd5.ExecuteScalar();
if (acType == "S")
{
SqlDataSource3.SelectCommand = ("select ac_desc from ac_mstr where gl_code='" + gl_code + "'");
subDrp.DataBind();
subDrp.Enabled = true;
//Response.Write("<script type='javacript/text'>alert('1')</script>");
}
else
{
subDrp.Enabled = false;
//Response.Write("<script type='javacript/text'>alert('2')</script>");
}
con.Close();
}
protected void saveRow(object sender, EventArgs e)
{
int SRno = Convert.ToInt32((Session["TransSrNo"]).ToString());
sda = new SqlDataAdapter("select * from tran_dtls where tc='" + Session["TC"] + "' and doc_no='" + Session["docNo"] + "' ", con);
build = new SqlCommandBuilder(sda);
//dt = new DataTable();
// DataSet ds = new DataSet();
sda.Fill(ds);
dt = (DataTable)ViewState["myViewState"];
if (Session["gridRow"] == null)
{
dt = ds.Tables[0];
dr = dt.NewRow();
dr["GL_code"] = GlDrp.SelectedValue;
dr["sub_code"] = subDrp.SelectedValue;
dr["particulars"] = partTxt.Text;
dr["chq_no"] = checkNoTxt.Text;
dr["chq_dt"] = checkDtTxt.Text;
dr["ref_no"] = refNoTxt.Text;
dr["ref_dt"] = refDtTxt.Text;
dr["dbcr"] = dbcrDrp.SelectedValue.ToString().Substring(0, 1);
dr["amt"] = amttxt.Text;
dr["job_no"] = jobNoTxt.Text;
dr["EMP"] = empDrop.SelectedValue;
dt.Rows.Add(dr);
dt.AcceptChanges();
ViewState["myViewState"] = dt;
//Session["gridRow"] = dt;
Session["gridRow"] = dt;
Session["saveToggle"] = "1";
closeFunction();
Response.Write("<script type='text/javascript'>this.close()</script>");
}
else
{
dt = (DataTable)Session["gridRow"];
dr = dt.NewRow();
dr["GL_code"] = GlDrp.SelectedValue;
dr["sub_code"] = subDrp.SelectedValue;
dr["particulars"] = partTxt.Text;
dr["chq_no"] = checkNoTxt.Text;
dr["chq_dt"] = checkDtTxt.Text;
dr["ref_no"] = refNoTxt.Text;
dr["ref_dt"] = refDtTxt.Text;
dr["dbcr"] = dbcrDrp.SelectedValue.ToString().Substring(0, 1);
dr["amt"] = amttxt.Text;
dr["job_no"] = jobNoTxt.Text;
dr["EMP"] = empDrop.SelectedValue;
dt.Rows.Add(dr);
dt.AcceptChanges();
ViewState["myViewState"] = dt;
//Session["gridRow"] = dt;
Session["gridRow"] = dt;
Session["saveToggle"] = "1";
//Response.Write("<script type='text/javascript'>window.opener.location.reload(true);</script>");
closeFunction();
Response.Write("<script type='text/javascript'>this.close()</script>");
}
}
private void closeFunction()
{
StringBuilder sb = new StringBuilder();
sb.Append("window.opener.RefreshPage();");
sb.Append("window.close();");
ClientScript.RegisterClientScriptBlock(this.GetType(), "CloseWindowScript", sb.ToString(), true);
}
}
Check your condition where you are doing : Response.Write. Both the conditions must be pointing out for first>
Related
I am new to c# and trying to search a listbox as following :
First i have this :
public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlCommand cmd;
SqlDataReader DataRead;
...
public FrmCodes()
{
InitializeComponent();
cmd = new SqlCommand("Select Item from Items", Cn);
Cn.Open();
DataRead = cmd.ExecuteReader();
while (DataRead.Read())
{
ListItems.Items.Add(DataRead["Item"].ToString());
}
DataRead.Close();
Cn.Close();
}
And tried to do this :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
while (DataRead.Read())
{
string str = DataRead["Item"].ToString();
string srch = txtSrch.Text;
if (str.Contains(srch))
{
ListItems.Items.Add(str);
}
}
}
It did not work , I tried to make a new sql select query that get data depending on txtSrch.Text but got nothing either .
Thanks in advance.
Edit#1
This is the query i mentioned before :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
SqlConnection Cn2 = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}
This did not affect the items in the listbox nothing happens on txtSrch Change .
Another solution using Dataview thanks to #Trevor
public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlDataAdapter da;
DataTable dt = new DataTable();
...
public FrmCodes()
{
InitializeComponent();
da = new SqlDataAdapter("Select Item from Items", Cn);
da.Fill(dt);
DataView dv = new DataView(dt);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}
Textbox change :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
DataView dv = new DataView(dt);
string srch = txtSrch.Text;
dv.RowFilter = string.Format("Item Like '%{0}%'", srch);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}
Thanks.
Basedon #Olivier Jacot-Descombes’ comments, this worked for me:
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
SqlConnection Cn2 = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}
I want to put a combobox in my datagridview. I've tried differents ways (creating a var list<>, creating an arraylist, ect...) and none is working. The thing is my column already exist because of my select query that show my database in the datagridview. But the column is empty since in my database the column is fill with NULL value.
I have two choices : Creating a combobox and do an addcolumn, or if you know how to do it link my combobox to the already existing column. And obviously i need help creating my combobox.
Thank you !
My code :
public partial class Repair : Form
{
public Repair()
{
Main pp = new Main();
InitializeComponent();
this.label4.Text = pp.label3.Text;
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE FComponent IS NOT NULL";
}
else
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "FaultCodeByOp";
combo.Name = "combo";
ArrayList list = new ArrayList();
list.Add("C-C");
list.Add("C-O");
combo.Items.AddRange(list.ToArray());
dataGridView1.Columns.Add(combo);
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for(int i=0;i<4;i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
foreach (DataGridViewRow row in dataGridView2.Rows)
{
for(int i=0;i<3;i++)
{
dataGridView2.Columns[i].ReadOnly = true;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Main ff = new Main();
ff.Show();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
string Var1 = textBox1.Text;
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailAndPass WHERE BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE SerialNum LIKE #SerialNum AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE SerialNum LIKE #SerialNum And FComponent IS NOT NULL";
}
}
else
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailOnly WHERE (BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent) AND ReportingOperator IS NULL ";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL ";
command1.CommandText = "SELECT DISTINCT Machine, BoardName, BoardNumber FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
}
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[6].Value != null) && (bool)row.Cells[6].Value)
{
SqlCommand command = maConnexion.CreateCommand();
command = new SqlCommand("update FailAndPass set FaultCodeByOp=#Fault, RepairingDate=#RD, RepairingTime = #RT, ReportingOperator=#RO WHERE SerialNum=#Serial", maConnexion);
command.Parameters.AddWithValue("#Fault", row.Cells[4].Value != null ? row.Cells[4].Value : DBNull.Value);
command.Parameters.AddWithValue("#RD", DateTime.Today.ToString("d"));
command.Parameters.AddWithValue("#RT", row.Cells[5].Value != null ? row.Cells[5].Value : DBNull.Value);
command.Parameters.AddWithValue("#RO", this.label4.Text);
command.Parameters.AddWithValue("#Serial", this.textBox1.Text);
command.ExecuteNonQuery();
}
}
maConnexion.Close();
this.Hide();
Repair rep = new Repair();
rep.Show();
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.IsCurrentRowDirty)
{
dataGridView1.Rows[e.RowIndex].Cells[6].Value = true;
}
}
}
private void ComboboxInDatagridview()
{
var dataGridView1 = new DataGridView();
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "FaultCodeByOp";
combo.Name = "combo";
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { combo });
ArrayList list = new ArrayList() { "C-C", "C-O" };
var rowindex = dataGridView1.Rows.Add();
DataGridViewComboBoxCell cmbCell = (DataGridViewComboBoxCell)dataGridView1["combo", rowindex];
//Or
//var columnindex = 0;
//DataGridViewComboBoxCell cmbCell = (DataGridViewComboBoxCell)dataGridView1[columnindex, rowindex];
cmbCell.DataSource = list;
}
Anyone having other solutions ? I've tried something else :
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
ArrayList list1 = new ArrayList(); //{ "C-C", "C-O", "Absence composant", "Mauvaise valeur", "Mauvais sens", "Mauvais composant" };
list1.Add("C-C");
list1.Add("C-O");
combo.DataSource = list1;
combo.HeaderText = "FaultCodeByOp";
combo.DataPropertyName = "FaultCodeByOp";
dataGridView1.Columns.AddRange(combo);
didnt change anything.
I dont know what i've done, but it is not greyish anymore. Now it is white like other columns.... but it doesnt dropdown, nor show members of the list.
Two Crystal reports
CrystalReport1.rpt
employeemonthly.rpt
Call these reports on signal aspx.net page.
protected void Button1_Click1(object sender, EventArgs e)
{
if (Page.IsValid)
{
if (rd.SelectedValue == "1")
{
DateTime to = Convert.ToDateTime(sdate.Text);
dbconnect a = new dbconnect();
ReportDocument rDoc = new ReportDocument();
a.OpenConnection();
a.cmd = new SqlCommand("viewattandace_repoeting",a.con);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
a.cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = a.cmd;
da.Fill(ds, "viewattandace_repoeting");
rDoc.Load(Server.MapPath("CrystalReport1.rpt"));
rDoc.SetDataSource(ds);
rDoc.SetParameterValue("date", to);
rDoc.SetParameterValue("depid", 1);
CrystalReportViewer1.ReportSource = rDoc;
CrystalReportViewer1.DataBind();
a.CloseConnection();
CleartextBoxes(this);
}
else
if (rd.SelectedValue == "2")
sd = Convert.ToDateTime(m.SelectedItem.Text + "/" + "1" + "/" + yt.SelectedItem.Text);
ed = LastDayOfMonth(sd);
dbconnect a = new dbconnect();
using (ReportDocument rDoc = new ReportDocument())
{
a.OpenConnection();
a.cmd = new SqlCommand("viewattandace_repoeting", a.con);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
a.cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = a.cmd;
da.Fill(ds, "viewattandace_repoeting");
rDoc.Load(Server.MapPath("employeemonthly.rpt"));
rDoc.SetDataSource(ds);
rDoc.SetParameterValue("sdate", sd);
rDoc.SetParameterValue("edate", ed);
rDoc.SetParameterValue("depid", 1);
rDoc.SetParameterValue("email", eet.Text.Trim());
CrystalReportViewer1.ReportSource = rDoc;
CrystalReportViewer1.DataBind();
a.CloseConnection();
}
}
}
}
view only one report at a time which dropdownlist selected index.
Now problem is view only first time selected report . when i selected other report then show this "parameter incorrect".
For Example
I selected CrystalReport1 report in dropdownlist and click button .Then report view ,then I selected employeemonthly report and click button then show this "parameter incorrect" and Vice versa.
I can solved this by add new CrystalReportViewer control
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (rd.SelectedValue == "1")
{
CrystalReportViewer2.Visible = false;
yl.Visible = false;
yt.Visible = false;
}
if (rd.SelectedValue == "2")
{
CrystalReportViewer1.Visible = false;
sdate.Visible = false;
}
}
**Button click code **
protected void Button1_Click1(object sender, EventArgs e)
{
if (Page.IsValid)
{
if (rd.SelectedValue == "1")
{
CrystalReportViewer1.Visible = true;
DateTime to = Convert.ToDateTime(sdate.Text);
dbconnect a = new dbconnect();
ReportDocument rDoc = new ReportDocument();
a.OpenConnection();
a.cmd = new SqlCommand("viewattandace_repoeting", a.con);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
a.cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = a.cmd;
da.Fill(ds, "viewattandace_repoeting");
rDoc.Load(Server.MapPath("CrystalReport1.rpt"));
rDoc.SetDataSource(ds);
rDoc.SetParameterValue("date", to);
rDoc.SetParameterValue("depid", 1);
CrystalReportViewer1.ReportSource = rDoc;
CrystalReportViewer1.DataBind();
CrystalReportViewer1.ToolPanelView = CrystalDecisions.Web.ToolPanelViewType.None;
a.CloseConnection();
}
else
if (rd.SelectedValue == "2")
{
CrystalReportViewer2.Visible = true;
sd = Convert.ToDateTime(m.SelectedItem.Text + "/" + "1" + "/" + yt.SelectedItem.Text);
ed = LastDayOfMonth(sd);
dbconnect a = new dbconnect();
ReportDocument rDoc = new ReportDocument();
a.OpenConnection();
a.cmd = new SqlCommand("viewattandace_repoeting", a.con);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
a.cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = a.cmd;
da.Fill(ds, "viewattandace_repoeting");
rDoc.Load(Server.MapPath("employeemonthly.rpt"));
rDoc.SetDataSource(ds);
rDoc.SetParameterValue("sdate", sd);
rDoc.SetParameterValue("edate", ed);
rDoc.SetParameterValue("depid", 1);
rDoc.SetParameterValue("email", eet.Text.Trim());
CrystalReportViewer2.ReportSource = rDoc;
CrystalReportViewer2.DataBind();
CrystalReportViewer2.ToolPanelView = CrystalDecisions.Web.ToolPanelViewType.None;
a.CloseConnection();
}
}
Please change if part of you code to
ReportDocument rDoc = new ReportDocument())
as you have it in else part
Below is my code C# net4 for sorting column in GridView but I've this error:
CS1502: The best overloaded method match for System.Data.DataView.DataView(System.Data.DataTable) has some invalid arguments
in this line why?: DataView sortedView = new DataView(GridViewBind());
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortingDirection = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
dir = SortDirection.Ascending;
sortingDirection = "Asc";
}
DataView sortedView = new DataView(GridViewBind());
sortedView.Sort = e.SortExpression + " " + sortingDirection;
GridView1.DataSource = sortedView;
GridView1.DataBind();
}
public void GridViewBind()
{
sql1 = " SELECT * FROM `tbl` ORDER BY empid DESC; ";
dadapter = new OdbcDataAdapter(sql1, myConnectionString);
dset = new DataSet();
dset.Clear();
dadapter.Fill(dset);
GridView1.DataSource = dset.Tables[0];
GridView1.DataBind();
dadapter.Dispose();
dadapter = null;
myConnectionString.Close();
}
The error is due to this line
DataView sortedView = new DataView(GridViewBind());
The function GridViewBind() return type is void which is incorrect. It should return a DataTable.
If it returns DataTable then your code will work.
You need to modify your function as follow
public DataTable GridViewBind()
{
sql1 = " SELECT * FROM `tbl` ORDER BY empid DESC; ";
dadapter = new OdbcDataAdapter(sql1, myConnectionString);
dset = new DataSet();
dset.Clear();
dadapter.Fill(dset);
DataTable dt=dset.Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
dadapter.Dispose();
dadapter = null;
myConnectionString.Close();
return dt;
}
Use DataView to sot the data.
public void GridViewBind()
{
sql1 = " SELECT * FROM `tbl` ORDER BY empid DESC; ";
dadapter = new OdbcDataAdapter(sql1, myConnectionString);
dset = new DataSet();
dset.Clear();
dadapter.Fill(dset);
DataTable dt = new DataTable();
dt=dset.Tables[0];
DataView dv = dt.DefaultView;
dv.Sort = "empid desc";
DataTable sortedDT = dv.ToTable();
GridView1.DataSource = sortedDT;
GridView1.DataBind();
dadapter.Dispose();
dadapter = null;
myConnectionString.Close();
}
I having problem on deleting a row of data returned by a search query.
I wish the user can select whichever row of data and click on the delete button [button1_click] to delete it from DB. This is a windows form application.
Hope you can advise me. Thanks a lot.
Below is my code
public partial class Search : Form
{
public Search()
{
InitializeComponent();
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;";
DataTable ds = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM staff", cn))
{
using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
adp.Fill(ds);
comboBox1.DataSource = ds;
comboBox1.ValueMember = "sname";
comboBox1.SelectedIndex = 0;
}
}
}
private void btn_search_bystaffname_Click(object sender, EventArgs e)
{
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;";
DataTable dt = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE sname = #sname", cn))
{
//cmd.Parameters.AddWithValue("#bdate", dtp_search_date.Value.Date);
cmd.Parameters.AddWithValue("#sname", comboBox1.SelectedValue);
using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd))
oda.Fill(dt);
GridView1.DataSource = dt;
GridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[3].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[0].HeaderText = "Booking ID";
GridView1.Columns[1].HeaderText = "Client Name";
GridView1.Columns[2].HeaderText = "Booking Date";
GridView1.Columns[3].HeaderText = "Booking Time";
GridView1.Columns[4].HeaderText = "Client Contact";
GridView1.Columns[5].HeaderText = "Staff Name";
this.GridView1.DefaultCellStyle.Font = new Font("Times New Roman", 12);
this.GridView1.DefaultCellStyle.ForeColor = Color.Blue;
this.GridView1.DefaultCellStyle.BackColor = Color.Beige;
this.GridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;
this.GridView1.DefaultCellStyle.SelectionBackColor = Color.Black;
this.GridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
}
}
}
private void btn_search_bydate_Click(object sender, EventArgs e)
{
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;";
DataTable dt = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE bdate = #bdate", cn))
{
cmd.Parameters.AddWithValue("#bdate", dtp_search_date.Value.Date);
cmd.Parameters.AddWithValue("#sname", comboBox1.SelectedValue);
using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd))
oda.Fill(dt);
GridView1.DataSource = dt;
GridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[3].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter;
GridView1.Columns[0].HeaderText = "Booking ID";
GridView1.Columns[1].HeaderText = "Client Name";
GridView1.Columns[2].HeaderText = "Booking Date";
GridView1.Columns[3].HeaderText = "Booking Time";
GridView1.Columns[4].HeaderText = "Client Contact";
GridView1.Columns[5].HeaderText = "Staff Name";
this.GridView1.DefaultCellStyle.Font = new Font("Times New Roman", 12);
this.GridView1.DefaultCellStyle.ForeColor = Color.Blue;
this.GridView1.DefaultCellStyle.BackColor = Color.Beige;
this.GridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;
this.GridView1.DefaultCellStyle.SelectionBackColor = Color.Black;
this.GridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
this.GridView1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
GridView1.Rows.Remove(row);
}
}
}
I'm assuming this is the method you want to change
private void button1_Click(object sender, EventArgs e)
{
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
GridView1.Rows.Remove(row);
}
This GridView1.Rows.Remove(row); will only remove the item from the DaDataGridViewRowCollection and will not remove it from the database.
To remove it from the database you can do one of the following
Remove it from `DataTable' and then use a DataAdapter and call update.
Directly delete it from the database using a DELETE SQL statement through a OleDbCommand.
If you choose option one you'd be well served by making dt a Field on your Form. This is because you can only access it now via ((DataRow)row.DataBoundItem).Table or GridView1.DataSource in the button1_Click event. Also making the DataAdapter a field would make this easier
e.g.
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
DataRow dRow = (DataRow)row.DataBoundItem;
dt.Rows.Remove(dRow);
Adapter.Update(dt);
As an aside you can choose to do only the dt.Rows.Remove(dRow); in the button1_Click and defer the Adapter.Update(dt) until later in a Save button.
If you go with option two you'll need to remove it from the DataTable or refresh the DataTable
e.g.
GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
DataGridViewRow row = GridView1.SelectedRows[0];
OleDbCommand cmd = new OleDbCommand(
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
// not 100% this delete syntax is correct for Access
using (var cmd = new OleDbCommand("DELETE booking WHERE [Booking ID] = #BookingId", cn))
{
cmd.Parameters.AddWithValue("#BookingId", dRow["Booking Id"]);
cmd.ExecuteNonQuery();
}
}
// Do this to update the in-memory representation of the Data
DataRow dRow = (DataRow)row.DataBoundItem;
dt.Rows.Remove(dRow);
// Or just refresh the datatable using code similar as your search methods
Here's how I've been doing it in my application (My unique identifier for the mysql table is in cell zero):
Oh, and dtcommand is a class instance for a database command class I use for common db stuff.
int userDeleteIndex;
if (int.TryParse(datagridview.Rows[rowIndex].Cells[0].Value.ToString(), out userDeleteIndex))
{
if (MessageBox.Show("Delete " + recordidentifyingdata + "? ", "Delete " + userDeleteIndex.ToString(), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
string updateUserSql = "DELETE FROM table WHERE user_id = " + userDeleteIndex.ToString() + "; ";
dtCommand.UpdateTable(updateUserSql);
InitializeUserDataView();
// Initalize userdataview refreshes the datagridview with the updated info
}
catch (Exception err)
{
Error trapping goes here
}
Here's the database update section from my class:
public int UpdateTable(string updateString, string MySqlConnectionString)
{
int returnValue = 0;
MySqlConnection connection = new MySqlConnection(MySqlConnectionString);
MySqlCommand command = new MySqlCommand(updateString, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception err)
{
WriteErrorLog("Unable to update table: " + err.ToString() +
" - Using SQL string: " + updateString + ".");
//MessageBox.Show("An error has occured while updating the database.\n" +
//"It has been written to the file: " + errorFile + ".", "Database Error");
returnValue = -1;
}
finally
{
connection.Close();
}
return (returnValue);
}