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();
}
Related
I want to select multiple item from checkbox list and then fill another check Box list on select index changed event of First check box list but after one selection its not working for another selected items because of "Auto Post Back = true" while debbuging i can see pointer start from page load event. I want after selection of all Item it should be fire "ddlregion_SelectedIndexChanged" so that I can able see all selected Item related value in another check Box List.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRegion();
}
}
Due to this its not fetching data for another selected Items how to solve this issues Please help me.
ddlRegion Code Binding:
public void BindRegion()
{
OracleCommand Cmd = new OracleCommand("select * from regions", con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlregion.DataSource = ds;
ddlregion.DataTextField = "REGION_DESC";
ddlregion.DataValueField = "REGION_CODE";
ddlregion.DataBind();
}
Select Index Changed Event
protected void ddlregion_SelectedIndexChanged(object sender, EventArgs e)
{
ddlDepot.Items.Clear();
ddlDepot.Items.Add(new ListItem("--Select Depot--", ""));
foreach (ListItem item in ddlregion.Items)
{
if (item.Selected == true)
{
string str = "select d.depot_code, d.depot_description from regions r, sub_regions sr, depots d where r.region_code = sr.region_code and sr.sub_region_code = d.sub_region_code and active = 'Y' and r.region_code in " + ddlregion.SelectedValue + "";
OracleCommand Cmd = new OracleCommand(str, con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlDepot.DataSource = ds;
ddlDepot.DataTextField = "DEPOT_DESCRIPTION";
ddlDepot.DataValueField = "DEPOT_CODE";
ddlDepot.DataBind();
}
}
}
You need to build your region list for the SQL, then once done call your SQL and Bind.
string regions = "";
bool regionSelected = false;
foreach (ListItem item in ddlregion.Items)
{
if (item.Selected == true)
{
regions += item.SelectedValue + ",";
regionSelected = true;
}
}
// looping done so clean up string for SQL
regions = "(" + regions.TrimEnd(',') + " )";
//only run if a region is selected
if(regionSelected)
{
string str = "select d.depot_code, d.depot_description from regions r, sub_regions sr,
depots d where r.region_code = sr.region_code and
sr.sub_region_code = d.sub_region_code and active = 'Y' and r.region_code
in " + regions;
OracleCommand Cmd = new OracleCommand(str, con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlDepot.DataSource = ds;
ddlDepot.DataTextField = "DEPOT_DESCRIPTION";
ddlDepot.DataValueField = "DEPOT_CODE";
ddlDepot.DataBind();
}
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
I want to Implement multiple search query system in Asp.Net where search input are in form of TEXTBOX and DROPDOWN LIST. Query should work in combination or indivisually to filter the data from SQL Server
and show in Gridview.
This Code Snippet is for filtering two Dropdown values:
if (Agree_type_srch.SelectedValue != null || Status_srch.SelectedValue != null)
{
if (Agree_type_srch.SelectedValue != null)
{
string connString = #"data source=ABC; database=XYZ; user id=sa; password=1234;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand com = new SqlCommand("Select *from EntryDatabase where Agree_type ='" + Agree_type_srch.SelectedItem.Text + "'", conn);
SqlDataAdapter sqldatad = new SqlDataAdapter();
DataSet ds = new DataSet();
com.Connection = conn;
sqldatad.SelectCommand = com;
using (DataTable dt = new DataTable())
{
sqldatad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
else if (Status_srch.SelectedValue != null)
{
string connString = #"data source=ABC; database=XYZ; user id=sa; password=1234;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand com = new SqlCommand("Select *from EntryDatabase where Curnt_St ='" + Status_srch.SelectedItem.Text + "'", conn);
SqlDataAdapter sqldatad = new SqlDataAdapter();
DataSet ds = new DataSet();
com.Connection = conn;
sqldatad.SelectCommand = com;
using (DataTable dt = new DataTable())
{
sqldatad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
if (Agree_type_srch.SelectedItem.Text != null && Status_srch.SelectedItem.Text != null)
{
string connString = #"data source=ABC; database=XYZ; user id=sa; password=1234;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand com = new SqlCommand("Select * from EntryDatabase where Agree_type ='" + Agree_type_srch.SelectedItem.Text + "'and Curnt_St ='" + Status_srch.SelectedItem.Text + "'", conn);
SqlDataAdapter sqldatad = new SqlDataAdapter();
DataSet ds = new DataSet();
com.Connection = conn;
sqldatad.SelectCommand = com;
using (DataTable dt = new DataTable())
{
sqldatad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
...
First, using string concatenation to provide parameters can result in SQL injection, use SqlParameter to pass parameters would be better.
Second, consider to warp all SqlClient classes by using scope so you don't have to worry close/dispose.
Lastly, For your question, you can use WHERE 1=1 then append any conditions you need.
Take your code as instance.
string connString = #"data source=ABC; database=XYZ; user id=sa; password=1234;";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
string query = "SELECT * FROM EntryDatabase WHERE 1=1";
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
if (Agree_type_srch.SelectedValue != null)
{
query += " AND Agree_type = #agree_type";
cmd.Parameters.AddWithValue("agree_type", Agree_type_srch.SelectedValue);
}
if (Status_srch.SelectedValue != null)
{
query += " AND Curnt_St = #curnt_st";
cmd.Parameters.AddWithValue("curnt_st", Status_srch.SelectedValue);
}
cmd.CommandText = query;
using (SqlDataAdapter sqldatad = new SqlDataAdapter())
{
DataSet ds = new DataSet();
sqldatad.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sqldatad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
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 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.