asp.net GridView RowDataBound smaller code - asp.net

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..

Related

i got an da.Fill(ds) error for my shopping card project in asp.net c#

public partial class AddToCart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("ProductID");
dt.Columns.Add("ProductName");
dt.Columns.Add("Price");
dt.Columns.Add("ProductImage");
dt.Columns.Add("Cost");
dt.Columns.Add("TotalCost");
if (Request.QueryString["id"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
String mycon = "Data Source=DESKTOP-8C66I6S/SQLEXPRESS;Initial Catalog=haritiShopping;Integrated Security=True";
SqlConnection scon = new SqlConnection(mycon);
String myquery = "select * from productdetail where ProductID=" + Request.QueryString["id"];
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = scon;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
dr["ProductID"] = ds.Tables[0].Rows[0]["ProductID"].ToString();
dr["ProductName"] = ds.Tables[0].Rows[0]["ProductName"].ToString();
dr["ProductImage"] = ds.Tables[0].Rows[0]["ProductImage"].ToString();
dr["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
}
else
{
dt = (DataTable)Session["buyitems"];
int sr;
sr = dt.Rows.Count;
dr = dt.NewRow();
String mycon = "Data Source=DESKTOP-8C66I6S/SQLEXPRESS;Initial Catalog=haritiShopping;Integrated Security=True";
SqlConnection scon = new SqlConnection(mycon);
String myquery = "select * from productdetail where ProductID=" + Request.QueryString["id"];
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = scon;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = sr + 1;
dr["ProductID"] = ds.Tables[0].Rows[0]["ProductID"].ToString();
dr["ProductName"] = ds.Tables[0].Rows[0]["ProductName"].ToString();
dr["ProductImage"] = ds.Tables[0].Rows[0]["ProductImage"].ToString();
dr["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
}
}
else
{
dt = (DataTable)Session["buyitems"];
GridView1.DataSource = dt;
GridView1.DataBind();
Update your connection string like below. You are missing to specify whether you want to use Windows Authentication or User Id & Password.
For Windows Authentication use Integrated Security=SSPI as below :
String mycon = "Data Source=DESKTOP-8C66I6S/SQLEXPRESS;Initial Catalog=haritiShopping;Integrated Security=SSPI";
For Authentication with User Id & Password add User Id & Password as below. Use original user id and password. I have taken sa for example. :
String mycon = "Data Source=DESKTOP-8C66I6S/SQLEXPRESS;Initial Catalog=haritiShopping;Integrated Security=True;user id=sa;password=sa";
Also you need to open connection with
SqlConnection scon = new SqlConnection(mycon);
scon.Open(); //Open connection
P.S. It is always recommended to Close connection too. Add scon.Open(); after da.Fill(ds); line. Why always close Database connection?
.
da.Fill(ds);
scon.Close(); //Close connection

PageIndexChanging error

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;
}

DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Disp_id'

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

Get the value of textbox in crystal report

I have crystal report, in which I need to get the value of textbox in crystal report. If I put textbox1= 1 then in crystal report it display as 1. How can I do this?
This is my crystal report code in default.aspx page.
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = "9";
TextBox2.Text = "02/02/2015";
TextBox3.Text = "02/03/2015";
DataTable dt = new DataTable();
String str = "select * from tbl1 where br=#search and Date between #search1 and #search2 ";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.Add("#search", SqlDbType.VarChar).Value = TextBox1.Text;
xp.Parameters.Add("#search1", SqlDbType.VarChar).Value = TextBox2.Text;
xp.Parameters.Add("#search2", SqlDbType.VarChar).Value = TextBox3.Text;
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
ReportDocument crystalReport = new ReportDocument();
crystalReport.Load(Server.MapPath("CrystalReport.rpt"));
crystalReport.SetDatabaseLogon("xx", "xxxx");
crystalReport.SetDataSource(dt);
CrystalReportViewer1.ReportSource = crystalReport;
CrystalReportViewer1.DataBind();
}
Here I need to display textbox1,2 and 3 value in crystal report
At first you have to create 3 parameters in CrystalReport toolbox under Parameter Fields as shown in the following figure.
Then you need to pass the values from your behind code
var rpt=new ReportDocument();
rpt.SetParameterValue("Search1","I am search1");
rpt.SetParameterValue("Search2","I am search2");
rpt.SetParameterValue("Search3","I am search3");
CrystalReportViewer1.ReportSource = rpt;
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = "9";
DataTable dt = new DataTable();
String str = "select * from tbl1 where br=#search and Date between #search1 and #search2 ";
SqlCommand xp = new SqlCommand(str, con);
xp.Parameters.Add("#search", SqlDbType.VarChar).Value = TextBox1.Text;
xp.Parameters.Add("#search1", SqlDbType.VarChar).Value = TextBox2.Text;
xp.Parameters.Add("#search2", SqlDbType.VarChar).Value = TextBox3.Text;
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
ReportDocument crystalReport = new ReportDocument();
crystalReport.SetParameterValue("search", "I am search");
crystalReport.Load(Server.MapPath("CrystalReport.rpt"));
crystalReport.SetDatabaseLogon("xx", "xxxx");
crystalReport.SetDataSource(dt);
CrystalReportViewer1.ReportSource = crystalReport;
CrystalReportViewer1.DataBind();
}
}
I have added the parameter name as search.
but it shows error invalid report path. If I remove this line crystalReport.SetParameterValue("search", "I am search"); then its working.

how to add data in the row from arraylist in asp.net?

i have a database..i am getting my database values in myarraylist..now i want to add this in my datatable column and finally bind it to gridview and show data in webpage..
mycodebehind page
protected void Page_Load(object sender, EventArgs e)
{
ArrayList myArrayList = ConvertDataSetToArrayList();
// Display each item of ArrayList
DataTable dt = new DataTable();
dt.Columns.Add("User Id", Type.GetType("System.String"));
dt.Columns.Add("Problem Name", Type.GetType("System.String"));
dt.Columns.Add("Status", Type.GetType("System.String"));
for (int i = 0; i < 2; i++)
{
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
public ArrayList ConvertDataSetToArrayList()
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM usertable", objsqlconn);
cmd.ExecuteNonQuery();
cmd.CommandType = CommandType.Text;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = cmd;
DataSet myDataSet = new DataSet();
myAdapter.Fill(myDataSet);
ArrayList myArrayList = new ArrayList();
foreach (DataRow dtRow in myDataSet.Tables[0].Rows)
{
myArrayList.Add(dtRow);
}
objsqlconn.Close();
return myArrayList;
}
i have problem in the for loop ..here how i will add rows and values to the columns from arraylist...
Do you mean something like this?
for (int i = 0; i < myArrayList.Count; i++)
{
var row = dt.NewRow();
row[0] = ((DataRow)myArrayList[i])[0];
row[1] = ((DataRow)myArrayList[i])[1];
row[2] = ((DataRow)myArrayList[i])[2];
dt.Rows.Add(row);
}
where indexes 0,1,2... can be replaced by column names "User Id", "Problem Name" and "Status"

Resources