Rows added but data not displayed on datagridview in vs2010 - c#-3.0

Here is my code; loaddata method extracts data from student table and it returns datatable named "tbl_std". from button click I want to load data into datagridview and code is below. It only displays number of blank rows that are in the database table but not data. Help me as soon as possible......
private DataTable loaddata()
{
sqlcon.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from student",sqlcon);
DataSet ds = new DataSet();
sqlcon.Close();
sda.Fill(ds, "tbl_std");
return ds.Tables["tbl_std"];
}
private void button4_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = loaddata();
}

Related

How to dynamically and correctly change a query in Command Table for Crystal Reports file?

I have many rpt files. I want to change the query for each report using C#. There are several ways to do this changes.
First way:
private void button_Test_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("D:\\Temp_01\\Report1_Test.rpt");
rptDoc.SetDatabaseLogon("User", "Password", "ServName", "DBName");
CrystalDecisions.Shared.ConnectionInfo ConnInf;
ConnInf = rptDoc.Database.Tables[0].LogOnInfo.ConnectionInfo;
String strSQLQuery = "SELECT TOP(123) * FROM sys.all_objects";
String strTableName = rptDoc.Database.Tables[0].Name;
try
{
rptDoc.SetSQLCommandTable(ConnInf, strTableName, strSQLQuery);
rptDoc.VerifyDatabase();
}
catch (Exception ex) { rptDoc.Close(); }
rptDoc.SaveAs("D:\\Temp_02\\Report2_Test.rpt");
rptDoc.Close();
}
It is not the best way. The method SetSQLCommand does not work when the query has any parameters. Even if you set value for each parameter, SetSQLCommand does not work. The example with a parameter which does not work:
private void button_Test_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("D:\\Temp_01\\Report1_Test.rpt");
rptDoc.SetDatabaseLogon("User", "Password", "ServName", "DBName");
CrystalDecisions.Shared.ConnectionInfo ConnInf;
ConnInf = rptDoc.Database.Tables[0].LogOnInfo.ConnectionInfo;
String strSQLQuery = "SELECT TOP(1) * FROM sys.all_objects WHERE name = {?strName}";
String strTableName = rptDoc.Database.Tables[0].Name;
try
{
rptDoc.SetParameterValue("strName", "Text");
rptDoc.SetSQLCommandTable(ConnInf, strTableName, strSQLQuery);
rptDoc.VerifyDatabase();
}
catch (Exception ex) { rptDoc.Close(); }
rptDoc.SaveAs("D:\\Temp_02\\Report2_Test.rpt");
rptDoc.Close();
}
It returns an error. This method does not work with parameters!
Second way:
private void button_Test_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("D:\\Temp_01\\Report1_Test.rpt");
rptDoc.SetDatabaseLogon("User", "Password", "ServName", "DBName");
ISCDReportClientDocument rcd = null;
rcd = rptDoc.ReportClientDocument as ISCDReportClientDocument;
CommandTable rTblOld;
CommandTable rTblNew;
rTblOld = rcd.Database.Tables[0] as CommandTable;
rTblNew = rcd.Database.Tables[0].Clone(true) as CommandTable;
rTblNew.CommandText = "SELECT TOP(1) * FROM sys.all_objects";
try
{
rcd.DatabaseController.SetTableLocationEx(rTblOld, rTblNew);
rcd.VerifyDatabase();
}
catch (Exception ex) { rcd.Close(); }
rcd.SaveAs(rcd.DisplayName, "D:\\Temp_02\\", 1);
rcd.Close();
}
This is also not the best way. The method SetLocalTableEx does a struct of the report is bad. After run SetLocalTableEx, attribute ConnectionInf.UserId have value NULL also the Name of connection
After SetTableLocationEx:
rcd.DatabaseController.SetTableLocationEx(rTblOld, rTblNew);
String UserID;
UserID = rptDoc.Database.Tables[0].LogOnInfo.ConnectionInfo.UserID;
if (UserID == null) MessageBox.Show("UserID has NULL");
UserId has value NULL
Also, before run SetTableLocationEx, Connection Name is MSODBCSQL11
enter image description here
After run SetTableLocationEx, Connection Name is Command
enter image description here
So,
how do dynamic and correctly to change the query in CommandTable for Crystal Reports file?
Thanks,
Artem
You are using command in Crystal Report which is the best way when doing and displaying a data from database to crystal report but unfortunately you do it in Code Behind.
My Question is:
Why don't you do it in Command of Crystal Report itself?
see this link for more info.

Crystal Report doesn't show data when generated

When I generate it on runtime, it doesn't show any data. But it does when I check on the 'Main Report Preview' of VS 2010. I have also checked my stored procedure, it does produce data when I execute it. What seems to be the problem?
This is my code in page_load:
protected void Page_Load(object sender, EventArgs e)
{
string municipio = Request.QueryString["municipio"];
string ano = Request.QueryString["ano"];
string cnpj = Server.UrlDecode(Request.QueryString["cnpj"]);
DataTable dt;
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection cnn = new SqlConnection(CS))
{
cnn.Open();
//stored procedure
SqlCommand cmd = new SqlCommand("spConsultaRelatorioCompleto", cnn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ano", ano);
cmd.Parameters.AddWithValue("#municipio", municipio);
cmd.Parameters.AddWithValue("#cnpj", cnpj);
//read access to the database
SqlDataReader dr = cmd.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmd);
//datatable with data
dt = new DataTable("dt");
//datatable with datareader's data
dt.Load(dr);
da.Fill(dt);
}
ReportDocument MeuRelatorio = new ReportDocument();
MeuRelatorio.Load(Server.MapPath("RelatorioConvenio.rpt"));
MeuRelatorio.SetDataSource(dt);
CrystalReportViewer1.ReportSource = MeuRelatorio;
}
}
}
I give some values in another webform when I click the button below:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Redirect("RelatorioGerado.aspx?municipio=" + ddlmunicipioconvenente.Text + "&cnpj=" + Server.UrlEncode(tbcnpjconvenente.Text) + "&ano=" + tbAno.Text);
}

Populate a combobox from an array list populated from an SQL statment

I am trying to populate a ComboBox with a list that is populated by a SQL statement.
I tried this:
public void buildData(){
ObservableList<ComboBox> data = FXCollections.observableArrayList();
Connection conn = db.makeConnection();
try{
String SQL = "Select Feature from FeaturesTable Order By Feature";
ResultSet rs = conn.createStatement().executeQuery(SQL);
while(rs.next()){
ComboBox cb = new ComboBox();
cb.featureCombo.set(rs.getString("Feature"));
featureCombo.add(cb);
}
featureCombo.setItems(data);
}
catch(Exception e){
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
I'm getting an error under cb.featureCombo.set of "featureCombo cannot be resolved or is not a field" but featureCombo exists as:
#FXML
private ObservableList<ComboBox> featureCombo;
and then another error under featureCombo.setItems(data); probably because of the same problem.
I'm not set on this method if someone has a better way to do this.
If you desire a ComboBox named featureCombo, you are going to have to declare it as a ComboBox and not as private ObservableList<ComboBox> featureCombo; which is making an ObservableList
Something like
#FXML
ComboBox<String> featureCombo;
Then in your method, you need to make a list of String to populate the ComboBox (you currently have a list of ComboBox)
public void buildData(){
ObservableList<String> data = FXCollections.observableArrayList(); //List of String
Connection conn = db.makeConnection();
try{
String SQL = "Select Feature from FeaturesTable Order By Feature";
ResultSet rs = conn.createStatement().executeQuery(SQL);
while(rs.next()){
data.add(rs.getString("Feature")); //add the String to the list
}
featureCombo.setItems(data); //Set the list of String as the data for your combo box
}
catch(Exception e){
e.printStackTrace();
System.out.println("Error on Building Data");
}
}

One to Many And Many To One Insert in Ef 6.0

A doctor have one degree and one degree have many doctors,
well when i try to add new doctor ef 6.0 (DbContext) insert the selected degree as new record in Degress Table
i don know why ?
Insert Method :
public bool Insert<T>(T entity) where T : class
{
bool result = false;
try
{
Context.Set<T>().Add(entity);
result = Context.SaveChanges() > 0;
}
catch (Exception exp)
{
result = false;
fnLogExceptions(exp);
}
return result;
}
The insert Section :
private void btnSave_Click(object sender, EventArgs e)
{
var dr = new DB.Doctors();
...
dr.Degrees = dropDownList_Degree.SelectedItem as DB.Degrees;
...
using (var ctx = new Context())
{
opState = ctx.Insert<DB.Doctors>(dr);
}
...
}
the new doctor is inserted successfully but also it insert new copy of selected degree
thanks in advance
The Degree that you were trying to assign isn't from the database, its from the dropodown list. So the EF thinks its new, therefore inserting a new Degree.
You need to retrieve the existing degree from the database.
var dr = new DB.Doctors();
int selectedDegreeID = (int)dropDownList_Degree.SelectedItem.Value;
using (var ctx = new Context())
{
dr.Degree = ctx.Degrees.Find(selectedDegreeID); // Retrieval and assignment.
opState = ctx.Insert<DB.Doctors>(dr);
}

Cascading dropdowns and control state (no AJAX, Jquery or Updated Panels)

I am having a weird post back problem. I have two dropdowns, project and charge codes. Projects selection populates the charge code drop down. I noticed that when I select a charge code, the value appears in the dropdown for a split second and then changes to the first choice in the dropdown. The Index change of that dropdown triggers and the value is the first option in the dropdown, not the one selected. I am not sure why it's doing this, but it must have something to do with postback. If it is a postback problem, is there a way to store the dropdown selection and restore the selection after re-load? Please don't suggest using AJAX or update panels, as we aren't allowed. Here is my asp code:
<p>
<asp:DropDownList ID="ddlProjects" runat="server"
onselectedindexchanged="ddlProjects_SelectedIndexChanged"
AutoPostBack="True" Visible="false" >
</asp:DropDownList>
</p>
<asp:DropDownList ID="ddlChargeCodes" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlChargeCodes_SelectedIndexChanged" Visible="false">
</asp:DropDownList>
<p>
and the C# code behind:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
LoadProjectsDropDown();
}
//Rest of Pageload Omitted....
// Initial Population of Project Dropdown
protected void LoadProjectsDropDown()
{
try
{ // Populate the Projects Drop Down from Table
ddlProjects.Items.Clear();
ddlProjects.DataSource = Time_Tracker.BLL.ProjectsManager.GetItems();
ddlProjects.DataTextField = "Project_Name";
ddlProjects.DataValueField = "Project_ID";
ddlProjects.DataBind();
ddlProjects.Items.Insert(0, new ListItem("PLEASE SELECT A PROJECT",
"PLEASE SELECT A PROJECT"));
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace,
#"Time_Tracker.txt");
}
}
// The Index Change portion of the Project Dropdown, which builds the Charge Code dropdown
protected void ddlProjects_SelectedIndexChanged(object sender, EventArgs e)
{
try
{ // When user selects the Project, Populate Charge Codes for the selected Project
ddlChargeCodes.Visible = true;
if (!string.IsNullOrEmpty(ddlProjects.SelectedValue))
{
ddlChargeCodes.Items.Clear();
ddlChargeCodes.DataSource = Time_Tracker.BLL.TasksManager.GetChargeCodes
(ddlProjects.SelectedValue);
ddlChargeCodes.DataTextField = "Description";
ddlChargeCodes.DataValueField = "Project_ID";
ddlChargeCodes.DataBind();
ddlChargeCodes.Items.Insert(0, new ListItem("PLEASE SELECT A CHARGE
CODE", "PLEASE SELECT A CHARGE CODE"));
Utilities.Project = Convert.ToInt16(ddlProjects.SelectedValue);
}
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}
// The Index Change of the Charge Codes Dropdown
protected void ddlChargeCodes_SelectedIndexChanged(object sender, EventArgs e)
{
try
{ // When user selects the Charge Code, it shows a summary and asks for the number of hours
Utilities.Description = Convert.ToString(ddlChargeCodes.SelectedItem);
Utilities.Chargecode = Convert.ToString(ddlChargeCodes.SelectedItem);
lblHoursLabel.Visible = true;
txtHours.Visible = true;
lblConfirmation.Visible = true;
btnStarOver.Visible = true;
btnOK.Visible = true;
lblConfirmation.Text = "Hours on " + Utilities.SelectedDate + " For Charge Code " + Utilities.Description;
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}
Did a lot of troubleshooting today. found that upon selecting the chargecode, it would do a pageload without triggering the "change index" event handler. Upon completion of pageload, it would trigger the index change event with the first selection (index 1) selected. Everyone I talked to said it should work the way it is. I finally wrote out the query/databind part of it to populate the dropdown instead of using the stored procedure and it now works. I have included the code change if it will help people in the future.
protected void ddlProjects_SelectedIndexChanged(object sender, EventArgs e)
{
try
{ // When user selects the Project, Populate Charge Codes for the selected Project
ddlChargeCodes.Visible = true;
if (!string.IsNullOrEmpty(ddlProjects.SelectedValue))
{
ddlChargeCodes.Items.Clear();
string strConn = Time_Tracker.DAL.DBUtils.SqlConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Charge_Code, Charge_Code + ' - ' + Description AS Description FROM [Time_Tracker].[dbo].[Tasks] WHERE Inactive = 0 AND Project_ID = " + ddlProjects.SelectedValue;
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddlChargeCodes.DataSource = objDs.Tables[0];
ddlChargeCodes.DataTextField = "Description";
ddlChargeCodes.DataValueField = "Charge_Code";
ddlChargeCodes.DataBind();
ddlChargeCodes.Items.Insert(0, "PLEASE SELECT A CHARGE CODE");
}
Utilities.Project = Convert.ToInt16(ddlProjects.SelectedValue);
}
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}