I am using Paging in my code and it throws error "The GridView 'GridView1' fired event PageIndexChanging which wasn't handled."
Following is my code (only the relevant part):
<asp:GridView ID="GridView1" runat="server" AllowPaging="true" PageSize="2"
OnPageIndexChanging="SubmitAppraisalGrid_PageIndexChanging">
</asp:GridView>
Code behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(#"select DB_monitor.name,
DB_monitor.priority, DB_alert.creationtime, DB_message.message from DB_alert
INNER JOIN DB_monitor on DB_alert.monitor = DB_monitor.ID
INNER JOIN DB_message on DB_alert.errmess = DB_message.ID
where DB_monitor.application = #strApplication and DB_monitor.instance =
#strInstances and DB_monitor.priority = #Priority and
DB_alert.creationtime between #FromDate and #ToDate and DB_alert.errmess != '1'"))
{
cmd.Parameters.Add("#strApplication", System.Data.SqlDbType.VarChar);// Set SqlDbType based on your DB column Data-Type
cmd.Parameters.Add("#strInstances", System.Data.SqlDbType.VarChar);
cmd.Parameters.Add("#Priority", System.Data.SqlDbType.Int);
cmd.Parameters.Add("#FromDate", System.Data.SqlDbType.DateTime);
cmd.Parameters.Add("#ToDate", System.Data.SqlDbType.DateTime);
cmd.Parameters["#strApplication"].Value = ddlApplication.SelectedValue;
cmd.Parameters["#strInstances"].Value = ddlInstances.SelectedValue;
cmd.Parameters["#Priority"].Value = ddlPriority.SelectedValue;
//2017-04-01 00:00:00.000
cmd.Parameters["#FromDate"].Value = Calendar1.SelectedDate.ToString("yyyy-MM-dd HH:mm:ss.fff");
cmd.Parameters["#ToDate"].Value = Calendar2.SelectedDate.ToString("yyyy-MM-dd HH:mm:ss.fff");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
} // [Edit: sic!]
}
Hi Aarthi, Do some changes in your code :-
protected void btnSubmit_Click(object sender, EventArgs e)
{
BindGridView();
}
protected void SubmitAppraisalGrid_PageIndexChanging(objectsender,GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView();
}
protected void BindGridView()
{
string constr = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(#"select DB_monitor.name,
DB_monitor.priority, DB_alert.creationtime, DB_message.message from DB_alert
INNER JOIN DB_monitor on DB_alert.monitor = DB_monitor.ID
INNER JOIN DB_message on DB_alert.errmess = DB_message.ID
where DB_monitor.application = #strApplication and DB_monitor.instance =
#strInstances and DB_monitor.priority = #Priority and
DB_alert.creationtime between #FromDate and #ToDate and DB_alert.errmess != '1'"))
{
cmd.Parameters.Add("#strApplication", System.Data.SqlDbType.VarChar);// Set SqlDbType based on your DB column Data-Type
cmd.Parameters.Add("#strInstances", System.Data.SqlDbType.VarChar);
cmd.Parameters.Add("#Priority", System.Data.SqlDbType.Int);
cmd.Parameters.Add("#FromDate", System.Data.SqlDbType.DateTime);
cmd.Parameters.Add("#ToDate", System.Data.SqlDbType.DateTime);
cmd.Parameters["#strApplication"].Value = ddlApplication.SelectedValue;
cmd.Parameters["#strInstances"].Value = ddlInstances.SelectedValue;
cmd.Parameters["#Priority"].Value = ddlPriority.SelectedValue;
//2017-04-01 00:00:00.000
cmd.Parameters["#FromDate"].Value = Calendar1.SelectedDate.ToString("yyyy-MM-dd HH:mm:ss.fff");
cmd.Parameters["#ToDate"].Value = Calendar2.SelectedDate.ToString("yyyy-MM-dd HH:mm:ss.fff");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
You have just declared Page index changing event in your aspx as OnPageIndexChanging="SubmitAppraisalGrid_PageIndexChanging" but have not defined same in your code behind
Just define event handler something like below in your code behind page
protected void GridView1_SubmitAppraisalGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = getGridData(); //get datasource for your grid in that method
GridView1.DataBind(); //bind the data
}
Find more at GridView.PageIndexChanging Event
And implement your getGridData() method using the code for fetching the data that written in button click and return data table so that will be assigned to Gridview's datasource.
public DataTable getGridData()
{
string constr = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(#"select DB_monitor.name,
DB_monitor.priority, DB_alert.creationtime, DB_message.message from DB_alert
INNER JOIN DB_monitor on DB_alert.monitor = DB_monitor.ID
INNER JOIN DB_message on DB_alert.errmess = DB_message.ID
where DB_monitor.application = #strApplication and DB_monitor.instance =
#strInstances and DB_monitor.priority = #Priority and
DB_alert.creationtime between #FromDate and #ToDate and DB_alert.errmess != '1'"))
{
cmd.Parameters.Add("#strApplication", System.Data.SqlDbType.VarChar);// Set SqlDbType based on your DB column Data-Type
cmd.Parameters.Add("#strInstances", System.Data.SqlDbType.VarChar);
cmd.Parameters.Add("#Priority", System.Data.SqlDbType.Int);
cmd.Parameters.Add("#FromDate", System.Data.SqlDbType.DateTime);
cmd.Parameters.Add("#ToDate", System.Data.SqlDbType.DateTime);
cmd.Parameters["#strApplication"].Value = ddlApplication.SelectedValue;
cmd.Parameters["#strInstances"].Value = ddlInstances.SelectedValue;
cmd.Parameters["#Priority"].Value = ddlPriority.SelectedValue;
//2017-04-01 00:00:00.000
cmd.Parameters["#FromDate"].Value = Calendar1.SelectedDate.ToString("yyyy-MM-dd HH:mm:ss.fff");
cmd.Parameters["#ToDate"].Value = Calendar2.SelectedDate.ToString("yyyy-MM-dd HH:mm:ss.fff");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
}
}
}
return dt;
}
Related
public partial class dispmgmt : System.Web.UI.Page
{
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click1(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvbind();
}
GridView1.Visible = true;
this.BindData();
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " Select DISTINCT CallType, Format, Disposition, SUbDisposition from CallCenter..Loy_DispMstr where CallType=#CallType and Format=#Format and Disposition = #Disposition and SubDisposition =#Disposition";
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
cmd.Parameters.AddWithValue("#CallType", ddlCalltype.SelectedValue);
cmd.Parameters.AddWithValue("#Format", ddlFormat.SelectedValue);
cmd.Parameters.AddWithValue("#Disposition ", ddlDisp.SelectedValue);
cmd.Parameters.AddWithValue("#SubDisposition", ddlSubdisp.SelectedValue);
cmd.Connection = con;
cmd.ExecuteNonQuery();
da.SelectCommand = cmd;
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void ddlCalltype_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCalltype.SelectedIndex != 0)
{
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet dsFormat = new DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Formatid,Formatdetail,dispformat From loy_Formatdetail with (nolock) Where isactive='1' and memberstatus = 'Member' order by FormatDetail";
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dsFormat);
ddlFormat.DataValueField = "DISPFORMAT";
ddlFormat.DataTextField = "FORMATDETAIL";
ddlFormat.DataSource = dsFormat.Tables[0];
ddlFormat.DataBind();
ddlFormat.Items.Insert(0, "<----Select---->");
}
else
{
ddlFormat.Items.Clear();
}
}
protected void ddlFormat_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlFormat.SelectedIndex != 0)
{
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con1 = new SqlConnection(strConnString);
con1.Open();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet dsDisp = new DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select DISTINCT Disposition from CallCenter..Loy_DispMstr where CallType=#CallType and SUBFormat=#Format";
cmd.Parameters.AddWithValue("#CallType", ddlCalltype.SelectedValue);
cmd.Parameters.AddWithValue("#Format", ddlFormat.SelectedItem.Text);
cmd.Connection = con1;
cmd.ExecuteNonQuery();
sda.SelectCommand = cmd;
sda.Fill(dsDisp);
ddlDisp.DataTextField = "Disposition";
ddlDisp.DataValueField = "Disposition";
ddlDisp.DataSource = dsDisp.Tables[0];
ddlDisp.DataBind();
ddlDisp.Items.Insert(0, "<----Select---->");
ddlDisp.Focus();
}
}
protected void ddlDisp_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlDisp.SelectedIndex != 0)
{
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd=new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet dsSubDisp = new DataSet();
using (cmd = new SqlCommand("Select distinct CallType,Disposition,SubDisposition,Format from Loy_DispMstr where CallType=#CallType and SUBFormat=#Format and Disposition = #disposition", con))
{
cmd.Parameters.AddWithValue("#CallType",ddlCalltype.SelectedValue);
cmd.Parameters.AddWithValue("#Format", ddlFormat.SelectedValue);
cmd.Parameters.AddWithValue("#disposition", ddlDisp.SelectedValue);
con.Open();
cmd.ExecuteNonQuery();
}
sda.SelectCommand = cmd;
sda.Fill(dsSubDisp);
{
ddlSubdisp.DataTextField = "SubDisposition";
ddlSubdisp.DataValueField = "SubDisposition";
ddlSubdisp.DataSource = dsSubDisp.Tables[0];
ddlSubdisp.DataBind();
ddlSubdisp.Items.Insert(0, "<----Select---->");
ddlSubdisp.SelectedIndex = 0;
ddlSubdisp.Focus();
// ddlDisp.Items.Insert(1, "ADD NEW VALUE");
// ddlDisp.SelectedIndex = 1;
// ddlDisp.Focus();
}
}
/* if (ddlDisp.SelectedItem.Text == "ADD NEW VALUE" )
{
TextBox1.Visible = true;
TextBox2.Visible = true;
}*/
}
protected void ddlSubdisp_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
DataSet dsOut = new DataSet();
SqlCommand cmd = new SqlCommand("select PID,Memberstatus,calltype,format,disposition,subdisposition, man_data,creation_date,createdby,updation_date,updatedby from Loy_SubPlaceholder");
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dsOut);
ddlDisp.DataSource = dsOut.Tables[0];
ddlDisp.DataValueField = "subdisposition";
ddlDisp.DataTextField = "subdisposition";
ddlDisp.DataBind();
con.Open();
cmd.ExecuteNonQuery();
}
private void BindData()
{
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
string query = " Select DISTINCT Disp_id ,CallType, Format, Disposition, SUbDisposition from CallCenter..Loy_DispMstr where CallType=#CallType and Format=#Format and Disposition = #Disposition and SubDisposition =#Disposition";
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#CallType", ddlCalltype.SelectedValue);
cmd.Parameters.AddWithValue("#Format", ddlFormat.SelectedValue);
cmd.Parameters.AddWithValue("#Disposition ", ddlDisp.SelectedValue);
cmd.Parameters.AddWithValue("#SubDisposition", ddlSubdisp.SelectedValue);
cmd.Connection = con;
cmd.ExecuteNonQuery();
da.SelectCommand = cmd;
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
Session["dstablegvassign"] = dt;
return dt;
}
}
}
}
protected void gvbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from dbo.Loy_DispMstr", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteid = (Label)row.FindControl("lblID");
con.Open();
SqlCommand cmd = new SqlCommand("delete FROM dbo.Loy_DispMstr where Disp_id='" + Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString()) + "'", con);
cmd.ExecuteNonQuery();
con.Close();
gvbind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
gvbind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int Disp_id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
//TextBox txtname=(TextBox)gr.cell[].control[];
TextBox textCallType = (TextBox)row.Cells[0].Controls[0];
TextBox textFormat = (TextBox)row.Cells[1].Controls[0];
TextBox textDisposition = (TextBox)row.Cells[2].Controls[0];
TextBox textSUBDisposition = (TextBox)row.Cells[3].Controls[0];
//TextBox textadd = (TextBox)row.FindControl("txtadd");
//TextBox textc = (TextBox)row.FindControl("txtc");
GridView1.EditIndex = -1;
con.Open();
//SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
SqlCommand cmd = new SqlCommand("update detail set CallType='" + textCallType.Text + "',Format='" + textFormat.Text + "',Disposition='" + textDisposition.Text + "',SUBDisposition='" + textSUBDisposition.Text + "'where id='" + Disp_id + "'", con);
cmd.ExecuteNonQuery();
con.Close();
gvbind();
//GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
gvbind();
}
protected void Button4_Click(object sender, EventArgs e)
{
string disp = TextBox1.Text.Trim();
if (!string.IsNullOrEmpty(disp))
{
ddlDisp.Items.Add(new ListItem(disp, disp));
}
}
You probably are using Disp_id somewhere in the GridView, like <%# Eval("Disp_id") %> or DataKeyNames="Disp_id". This does mean that Disp_id must be present in every database result set that is bound to the GridView.
And it's at least missing in the query inside Button2_Click1
I have a web form that uses a text box to update a comments field in the database. I would like to check for a blank before update and have a reminder box that says "Comment section blank, continue?", then have a yes / no option. This would allow the user to return to the update without making changes. The text box is visible when the user selects edit on the row in a gridview. I will provide code below so that anyone can see what I am doing. If this cannot be done this way, simply a message box saying that the comment section is blank would suffice.
Here is the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;
namespace AnnoTracker
{
public partial class WebForm1 : System.Web.UI.Page
{
public static class MyVariables
{
public static int PI = 0;
public static string JN = "";
public static string ST = "";
public static string AT = "";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
dlAnnoType.SelectedValue = "Agency Error";
}
}
protected void EditSummary(object sender, GridViewEditEventArgs e)
{
gvSummary.EditIndex = e.NewEditIndex;
string _custName = gvSummary.DataKeys[e.NewEditIndex].Value.ToString();
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvSummary.EditIndex = -1;
BindData();
}
protected void gvSummary_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvSummary.PageIndex = e.NewPageIndex;
MyVariables.PI = e.NewPageIndex;
BindData();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvSummary.EditIndex == e.Row.RowIndex)
{
DropDownList dlBU = (DropDownList)e.Row.FindControl("dlBU");
string _custName = gvSummary.DataKeys[e.Row.RowIndex].Values[1].ToString();
string BUquery = "select distinct Unit from vw_BU where Business='" + _custName + "'";
SqlCommand BUcmd = new SqlCommand(BUquery);
dlBU.DataSource = GetData(BUcmd);
dlBU.DataTextField = "Unit";
dlBU.DataValueField = "Unit";
dlBU.DataBind();
dlBU.Items.FindByValue((e.Row.FindControl("lblBU") as Label).Text).Selected = true;
DropDownList dlPA = (DropDownList)e.Row.FindControl("dlPA");
string _PAcustName = gvSummary.DataKeys[e.Row.RowIndex].Values[1].ToString();
string PAquery = "select PA from PA where Business='" + _PAcustName + "' order by PA";
SqlCommand PAcmd = new SqlCommand(PAquery);
dlPA.DataSource = GetData(PAcmd);
dlPA.DataTextField = "PA";
dlPA.DataValueField = "PA";
dlPA.DataBind();
dlPA.Items.FindByValue((e.Row.FindControl("lblPA") as Label).Text).Selected = true;
DropDownList dlET = (DropDownList)e.Row.FindControl("dlET");
string ETquery = "select distinct ErrorType from ErrorType order by ErrorType";
SqlCommand ETcmd = new SqlCommand(ETquery);
dlET.DataSource = GetData(ETcmd);
dlET.DataTextField = "ErrorType";
dlET.DataValueField = "ErrorType";
dlET.DataBind();
dlET.Items.FindByValue((e.Row.FindControl("lblET") as Label).Text).Selected = true;
DropDownList dlAA = (DropDownList)e.Row.FindControl("dlAA");
string AAquery = "select distinct AAA from ActualAgencyError";
SqlCommand AAcmd = new SqlCommand(AAquery);
dlAA.DataSource = GetData(AAcmd);
dlAA.DataTextField = "AAA";
dlAA.DataValueField = "AAA";
dlAA.DataBind();
dlAA.Items.FindByValue((e.Row.FindControl("lblAA") as Label).Text).Selected = true;
}
}
protected void UpdateSummary(object sender, GridViewUpdateEventArgs e)
{
string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
string ET = (gvSummary.Rows[e.RowIndex].FindControl("dlET") as DropDownList).SelectedItem.Value;
string AA = (gvSummary.Rows[e.RowIndex].FindControl("dlAA") as DropDownList).SelectedItem.Value;
string PA = (gvSummary.Rows[e.RowIndex].FindControl("dlPA") as DropDownList).SelectedValue;
string AnnotationNumber = gvSummary.DataKeys[e.RowIndex].Value.ToString();
string sgkComments = (gvSummary.Rows[e.RowIndex].FindControl("tbsgkComm") as TextBox).Text;
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
string query = "update vw_GridviewSource set [BusinessUnit] = #BU, [ErrorType] = #ET, [sgkComments] = #sgk, [ActualAgencyError] = #AA, [PA] = #PA where [AnnotationNumber] = #AnnoNum";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#BU", BU);
cmd.Parameters.AddWithValue("#AnnoNum", AnnotationNumber);
cmd.Parameters.AddWithValue("#ET", ET);
cmd.Parameters.AddWithValue("#AA", AA);
cmd.Parameters.AddWithValue("#sgk", sgkComments);
cmd.Parameters.AddWithValue("#PA", PA);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
//gvSummary.DataBind();
BindData();
}
private void BindData()
{
if (MyVariables.JN != "" && MyVariables.ST != "" && MyVariables.AT != "")
{
dlJobName.SelectedValue = MyVariables.JN;
dlJobName.DataBind();
dlStage.SelectedValue = MyVariables.ST;
dlStage.DataBind();
dlAnnoType.SelectedValue = MyVariables.AT;
dlAnnoType.DataBind();
}
String conString = System.Configuration.ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
string query = "select [Page_ID],[AnnotationNumber],[AnnotationBy],[PA],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource order by [Page_ID]";
SqlCommand cmd = new SqlCommand();
if (dlJobName.SelectedValue != "" & dlStage.SelectedValue != "")
{
query = "select [Page_ID],[AnnotationNumber],[AnnotationBy],[PA],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource where Name = '" + dlJobName.SelectedValue + "' and AnnotationDate = '" + dlStage.SelectedValue + "' order by [Page_ID]";
//cmd.Parameters.AddWithValue("#Name", dlJobName.SelectedValue);
//cmd.Parameters.AddWithValue("#Stage", dlStage.SelectedValue);
}
if (dlAnnoType.SelectedValue != "" && (dlJobName.SelectedValue != "" && dlStage.SelectedValue != ""))
{
query = "select [Page_ID],[AnnotationNumber],[AnnotationBy],[PA],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource where AnnotationType = '" + dlAnnoType.SelectedValue + "' and Name = '" + dlJobName.SelectedValue + "' and AnnotationDate = '" + dlStage.SelectedValue + "' order by [Page_ID]";
}
if (dlAnnoType.SelectedValue != "" && (dlJobName.SelectedValue.Length < 2 && dlStage.SelectedValue.Length < 2) )
{
query = "select [Page_ID],[AnnotationNumber],[AnnotationBy],[PA],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource where AnnotationType = '" + dlAnnoType.SelectedValue + "' order by [Page_ID]";
}
cmd.CommandText = query;
SqlConnection con = new SqlConnection(conString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
gvSummary.DataSource = ds;
gvSummary.PageIndex = MyVariables.PI;
gvSummary.DataBind();
//string #Name;
//string #Stage;
//#Name = dlJobName.SelectedValue;
//#Stage = dlStage.SelectedValue;
//string query = "select [AnnotationNumber],[AnnotationBy],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust from vw_GridviewSource where Name = '" + #Name + "' and AnnotationDate = '" + #Stage + "'";
//SqlCommand cmd = new SqlCommand(query);
//gvSummary.DataSource = GetData(cmd);
//gvSummary.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
protected void dlJobName_SelectedIndexChanged(object sender, EventArgs e)
{
MyVariables.JN = dlJobName.SelectedValue;
dlStage.DataBind();
MyVariables.ST = dlStage.SelectedValue;
gvSummary.DataBind();
BindData();
}
protected void dlStage_SelectedIndexChanged(object sender, EventArgs e)
{
MyVariables.JN = dlJobName.SelectedValue;
//dlStage.DataBind();
MyVariables.ST = dlStage.SelectedValue;
MyVariables.AT = dlAnnoType.SelectedValue;
gvSummary.DataBind();
BindData();
}
protected void dlAnnoType_SelectedIndexChanged(object sender, EventArgs e)
{
MyVariables.AT = dlAnnoType.SelectedValue;
MyVariables.JN = dlJobName.SelectedValue;
//dlStage.DataBind();
MyVariables.ST = dlStage.SelectedValue;
gvSummary.DataBind();
BindData();
}
}
}
You show only server side code, and it's more complicated doing chek on server side and show message on client.
Simple sample of chek on client side by javascript:
<script type="text/javascript">
function MyConfirm() {
if (document.getElementById("tb1").value == '')
if (confirm("Comment section blank, continue?"))
return true;
else
return false;
else true;
}
</script>
<asp:TextBox runat="server" ID="tb1" />
<asp:Button runat="server" ID="btn1" onclick="btn1_Click" OnClientClick="return MyConfirm();" Text="Save" />
i am trying to do sorting and paging for my gridview without datasource but when i click on the header of the gridview to sort it , nothing happen but when i click for paging is working fine and there is no error. how to do about it?
this is my code:
protected void Page_Load(object sender, EventArgs e)
{
dbBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtSortTable = GridView1.DataSource as DataTable;
if (dtSortTable != null)
{
DataView dvSortedView = new DataView(dtSortTable);
dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
GridView1.DataSource = dvSortedView;
GridView1.DataBind();
}
}
private string getSortDirectionString(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
if(sortDirection== SortDirection.Ascending)
{
newSortDirection = "ASC";
}
else
{
newSortDirection = "DESC";
}
return newSortDirection;
}
private void dbBind()
{
DataSet ds;
string startdate = (string)(Session["startdate"]);
string enddate = (string)(Session["enddate"]);
var format = "dd/MM/yyyy";
DateTime one = DateTime.ParseExact(startdate, format, CultureInfo.InvariantCulture);
DateTime two = DateTime.ParseExact(enddate, format, CultureInfo.InvariantCulture);
if (two >= one)
{
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=n;Integrated Security=True");
//conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [AmountSpent], [TimeDate]=convert(nvarchar,timedate,103), [StallNo] FROM [StudentTransactions] WHERE TimeDate BETWEEN #one AND #two", conn);
cmd.Parameters.AddWithValue("#one", one);
cmd.Parameters.AddWithValue("#two", two);
ds = new DataSet();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
if (ds.Tables.Count > 0)
{
DataView dv = ds.Tables[0].DefaultView;
if (ViewState["SortDirection"] != null)
{
sortDirection = ViewState["SortDirection"].ToString();
}
if (ViewState["SortExpression"] != null)
{
sortExpression = ViewState["SortExpression"].ToString();
dv.Sort = string.Concat(sortExpression, " ", sortDirection);
}
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
//GridView1.DataBind();
//conn.Close();
}
else
{
GridView1.Visible = false;
string strMsg = " Data not found for the choosen dates.";
Response.Write("<script>alert('" + strMsg + "')</script>");
}
}
I am trying to fill a gridview by taking data from multiple tables. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string query = "SELECT RegisterTable.CourseCode,
RegisterTable.courseNumber,
RegisterTable.Term,RegisterTable.Grade,
CourseTable.CourseName,
CourseTable.Level,
CourseTable.Credit
FROM RegisterTable,CourseTable
WHERE StudentID='" + MyGlobals.currentID + "' and
RegisterTable.CourseCode=CourseTable.CourseCode and
RegisterTable.CourseNumber=CourseTable.CourseNumber and
RegisterTable.Term=CourseTable.Term";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
GridView1.DataSource = tab;
GridView1.DataBind();
}
This gives an error saying that "Incorrect syntax near the keyword 'where'." Can anyone help me with this? Thanks
EDIT:
Ignore the string's lack of concatenation. It was all on one line and you had to scroll for a mile to see it all. They just made it easier to see.
Have you tried re-writing your query (so it's not using a cross-join)?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = null;
SqlCommand cmd = null;
SqlDataAdapter adap = null;
string query = string.Empty();
DataSet ds = null;
DataTable tab = null;
con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
query = "SELECT RegisterTable.CourseCode, RegisterTable.CourseNumber, RegisterTable.Term, RegisterTable.Grade, CourseTable.CourseName, CourseTable.Level, CourseTable.Credit FROM RegisterTable INNER JOIN CourseTable ON RegisterTable.CourseCode = CourseTable.CourseCode AND RegisterTable.CourseNumber = CourseTable.CourseNumber AND RegisterTable.Term = CourseTable.Term WHERE StudentID = #StudentID;";
cmd = new SqlCommand(query, con);
cmd.Parameters.Add("StudentID", SqlDbType.VarChar, 50).Value = MyGlobals.currentID;
ds = new DataSet();
adap = new SqlDataAdapter(cmd);
adap.Fill(ds);
if (ds.Tables.Count > 0) {
tab = ds.Tables(0);
}
GridView1.DataSource = tab;
GridView1.DataBind();
}
im working on asp.net and c#.
I have a gridview populated from an sql database. I have dropdowlist and textbox controls.
On the RowDataBound event I have values asigned to controls:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Control ctrlgridEstacion = e.Row.FindControl("grid1");
if (ctrlgridEstacion != null)
{
DropDownList dd = ctrlgridEstacion as DropDownList;
SqlDataReader dr;
SqlCommand cmd;
cmd = new SqlCommand();
cmd.Connection = sqlConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_load";
sqlConn.Open();
dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dd.DataSource = dt;
dd.DataValueField = "code";
dd.DataTextField = "code";
dd.DataBind();
DataRowView rowView = (DataRowView)e.Row.DataItem;
string tempDate = rowView["code"].ToString();
dd.SelectedIndex = dd.Items.IndexOf(dd.Items.FindByText(tempDate));
sqlConn.Close();
}
Control gridPrefijo = e.Row.FindControl("grid2");
if (gridPrefijo != null)
{
TextBox dd = gridPrefijo as TextBox;
DataTable dt = new DataTable();
sqlConn.Open();
SqlCommand cmd;
cmd = new SqlCommand();
cmd.Connection = sqlConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_load";
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
int startIndex;
if (c1 < 1)
{
int RC = dt.Rows.Count;
int PS = GridView1.PageSize;
int PN = GridView1.PageIndex + 1;
startIndex = (PN - 1) * PS;
int endIndex = Math.Min(RC - 1, startIndex + PS - 1);
dri = startIndex;
}
if (dt.Rows.Count > 0)
{
dd.Text = dt.Rows[dri ]["name"].ToString();
c1++;
}
sqlConn.Close();
}
}
}
The problem is that I have 15 controls, so adding them to the RowDatabound event is a lot of code.
How can I make the code smaller?
Thanks..