ObjectDatasource passing parameters - asp.net-3.5

I want to Insert data from textboxes using ObjectDatasource. The ObjectDataSource is bound to a gridview but displays certain computed columns only. The Textboxes are used to input all the basic inputs.
ObjectDatasource Delete & Select commands (Link buttons on gridview) are working. However I am having trouble with Insert command. I am not able to figure out how to pass the data from the textboxes as parameters to the ObjectDataSource Insert
EDIT: With the code below, a record is getting inserted. Parameters are getting passed. odssMain.Insert() gives the Error: "Object reference not set to an instance of an object".
EDIT: WHY AM I GETTING THIS ERROR?
Also the ObjectDataSource has been acting weird. After an error, I have to reconfigure the Insert Method again on the ODS Wizard as the method will be blank.
ASP.NET 3.5 & SQL 2008, VS 2008.
Here's my code:
<asp:ObjectDataSource ID="odsMain" runat="server"
SelectMethod="SelectMain" DeleteMethod="DeleteMain"
InsertMethod="InsertMain" UpdateMethod="UpdateMain"
OldValuesParameterFormatString="original_{0}" TypeName="MainDB" >
.......
<InsertParameters>
<asp:Parameter Name="Quantity" Type="Int32" />
</InsertParameters>
DAL FILE:
[DataObjectMethod(DataObjectMethodType.Insert)]
public static int InsertMain(int Quantity)/
{
SqlConnection con = new SqlConnection(GetConnectionString());
string strQuery = "INSERT INTO t_Main (Quantity) VALUES (#Quantity)";
SqlCommand cmd = new SqlCommand(strQuery, con);
cmd.Parameters.AddWithValue("#Quantity", Quantity);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
CODE BEHIND FILE:
protected void btnSaveAnalysis_Click(object sender, EventArgs e)
{
odsMain.InsertParameters.Clear();
//Store parameters with values to the collection
odsMain.InsertParameters.Add(new Parameter ("Quantity", TypeCode.Int32, iQuantity.ToString()));
//Diferent ways that I tried. Still not working
//odsMain.InsertParameters.Add("Quantity", iQuantity.ToString());
//odsMain.InsertParameters["Quantity"].DefaultValue = iQuantity.ToString();
odsMain.Insert();
}

you could try like this....
ObjectDataSource for InsertParameter looks like below one
<InsertParameters>
<asp:Parameter Name="FirstName" />
<asp:Parameter Name="MiddleName" />
<asp:Parameter Name="LastName" />
<asp:Parameter Name="Desgination" />
<asp:Parameter Name="Address" />
<asp:Parameter Name="City" />
<asp:Parameter Name="State" />
<asp:Parameter Name="Country" />
</InsertParameters>
I will also pass InsertMethod property of ObjectDataSource,which will have an InsertCustomer method.
InsertCustomer method looks like below one :-
public void InsertCustomer(string FirstName, string MiddleName,string LastName, string Desgination, string Address, string City, string State, string Country)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("InsertCustomer", con);
cmd.CommandType = CommandType.StoredProcedure;
//this check is necessary, when u don't pass any value as it will pass as [default] and will give error
if (string.IsNullOrEmpty(FirstName))
FirstName = string.Empty;
if (string.IsNullOrEmpty(LastName))
LastName = string.Empty;
if (string.IsNullOrEmpty(MiddleName))
MiddleName = string.Empty;
if (string.IsNullOrEmpty(Desgination))
Desgination = string.Empty;
if (string.IsNullOrEmpty(Address))
Address = string.Empty;
if (string.IsNullOrEmpty(City))
City = string.Empty;
if (string.IsNullOrEmpty(State))
State = string.Empty;
if (string.IsNullOrEmpty(Country))
Country = string.Empty;
cmd.Parameters.AddWithValue("#IV_FirstName", FirstName);
cmd.Parameters.AddWithValue("#IV_LastName", LastName);
cmd.Parameters.AddWithValue("#IV_MiddleName", MiddleName);
cmd.Parameters.AddWithValue("#IV_Desgination", Desgination);
cmd.Parameters.AddWithValue("#IV_Address", Address);
cmd.Parameters.AddWithValue("#IV_City", City);
cmd.Parameters.AddWithValue("#IV_State", State);
cmd.Parameters.AddWithValue("#IV_Country", Country);
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
Button Save for inserting record.
//Insert record Save Button
protected void btnSave_Click(object sender, EventArgs e)
{
Customer.InsertParameters["FirstName"].DefaultValue = GetGridTextBoxValue("txtFirstName");
Customer.InsertParameters["MiddleName"].DefaultValue = GetGridTextBoxValue("txtMiddleName");
Customer.InsertParameters["LastName"].DefaultValue = GetGridTextBoxValue("txtLastName");
Customer.InsertParameters["Desgination"].DefaultValue= GetGridTextBoxValue("txtDesgination");
Customer.InsertParameters["Address"].DefaultValue = GetGridTextBoxValue("txtAddress");
Customer.InsertParameters["City"].DefaultValue = GetGridTextBoxValue("txtCity");
Customer.InsertParameters["State"].DefaultValue = GetGridTextBoxValue("txtState");
Customer.InsertParameters["Country"].DefaultValue = GetGridTextBoxValue("txtCountry");
Customer.Insert();
}
GetGridTextBoxValue function will get TextBox text value from footer row of respective column.
//Get TextBox value of GridView Footer Row
public string GetGridTextBoxValue(string txtID)
{
try
{
TextBox txt = (TextBox)gvCustomer.FooterRow.FindControl(txtID); // here you can place any text box value on your design page
return txt.Text;
}
catch (Exception ex)
{
return string.Empty;
throw ex;
}
}
and the results image is like this ...

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.

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

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

Ajaxcontroltoolkit AutocompleteExtender Timeout related

I am trying to use the AjaxControlToolkit Autocompleteextender (for Visual Studio 2008 having ToolkitScriptManager) with values returned from database to be suggested. When I am returning a simple string array it is working fine. But when I am trying to pull data from the database, it is not working. Below is my web service code and the Autocompleteextender Html. When I am running the following without breakpoints no error is thrown but does not work. And when I put breakpoints I am getting javascript error "Microsoft JScript runtime error: Sys.ParameterCountException: Parameter count mismatch."
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod]
public string[] GetAgentCompanyAutoCompleteList(string prefixText, int count, string contextKey)
{
//return new string[] { "aaaaaaa", "bbbbbb" };
string sql = string.Format("select distinct AgentCompany from Realtors where FK_CompanyID = {0} Order By AgentCompany", contextKey);
string[] items = new string[] { "" };
string cn = "Data Source=localhost;Initial Catalog=ABCD;Integrated Security=True";
using (SqlDataAdapter da = new SqlDataAdapter(sql, cn))
{
DataTable dt = new DataTable();
da.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
for (int i = 0; i < dt.Rows.Count; i++)
items[i] = dt.Rows[i]["AgentCompany"].ToString();
}
return items;
}
}
<asp:TextBox ID="txtCompany" runat="server" MaxLength="256" Width="150px">/asp:TextBox>
<ajax:AutoCompleteExtender
ID="AutoCompleteExtender1"
runat="server"
EnableCaching="true"
MinimumPrefixLength="1"
TargetControlID="txtCompany"
ServicePath="~/AutoComplete.asmx"
ServiceMethod="GetAgentCompanyAutoCompleteList"
UseContextKey="true">
</ajax:AutoCompleteExtender>

C# Sending GridViews/DataTables via Email

I'm trying the find the best way to send a GridView or DataTable in an email.
Page Behind Code:
protected void Page_Load(object sender, EventArgs e)
{
DataTable s1 = Sql.specificReportData(Convert.ToInt32(Session["userID"]));
this.gv.DataSource = s1.DefaultView;
this.gv.DataBind();
}
This generates and binds the data successfully, but if I try and add the contents of gv to a HTML encoded email then the gv part of the email is blank. Do I need to alter the GridView so it's HTML compliant? I can't find an example of how to do this. Any help appreciated.
edit: Gave answer to Solairaya as he gave fuller example, as well as object flushing and disposal. Marked both answers up as they both helped
Page behind code
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = getHTML(GridView1);
}
private string getHTML(GridView gv)
{
StringBuilder sb = new StringBuilder();
StringWriter textwriter = new StringWriter(sb);
HtmlTextWriter htmlwriter = new HtmlTextWriter(textwriter);
gv.RenderControl(htmlwriter);
htmlwriter.Flush();
textwriter.Flush();
htmlwriter.Dispose();
textwriter.Dispose();
return sb.ToString();
}
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
Page code
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT [UserID], [Name], [Email] FROM [WEB_Users] WHERE ([Name] LIKE '%' + #Name + '%')">
<SelectParameters>
<asp:Parameter DefaultValue="%Moha%" Name="Name" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
</form>
Hai alex try this,
Try this (C#):
using System.IO;
using System.Text;
using System.Net.Mail;
private string GridViewToHtml(GridView gv)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.RenderControl(hw);
return sb.ToString();
}
protected void SendMailButton_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.Body = GridViewToHtml(GridView1);
mail.IsBodyHtml = true;
......
}
public override void VerifyRenderingInServerForm(Control control)
{
}