从组合选择的值中将此值传递到存储过程,并使用序列化生成条形图仪表板。但这向我显示了一个错误
无法将字符串隐式转换为system.data.datatable
使用DataTable和序列化
此行错误
return serializer.Serialize(rows);
.cs代码
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.Configuration;
using System.Data.SqlClient;
namespace VOT.DashboardPages
{
public partial class Velocity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT ProjectNo FROM [dbo].[ProjectPlan] ORDER BY ProjectNo asc"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
ddlProjectNo.DataSource = cmd.ExecuteReader();
ddlProjectNo.DataTextField = "ProjectNo";
ddlProjectNo.DataValueField = "ProjectNo";
ddlProjectNo.DataBind();
con.Close();
}
}
ddlProjectNo.Items.Insert(0, new ListItem("--Select ProjectNo--", "0"));
}
}
public DataTable BindData(String prjNo)
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection("constr");
try
{
connection.Open();
SqlCommand sqlcmd = new SqlCommand("VelocityByOperationType", connection);
sqlcmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlcmd);
sqlcmd.Parameters.AddWithValue("@prjNo", prjNo);
sqlDa.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
finally
{
connection.Close();
}
}
protected void ddlProjectNo_SelectedIndexChanged(object Sender,EventArgs e)
{
TextBox1.Text = ddlProjectNo.SelectedItem.Value;
DataTable dt = BindData(ddlProjectNo.SelectedItem.Value);
//if(dt.Rows.Count>0)
//{
//}
}
}
答案 0 :(得分:1)
Serialize方法返回一个字符串,而不是DataTable。
如果要从方法中返回数据表,则需要用以下内容替换返回的变量(第68行):
return dt;
这将在调用该方法时从该方法返回具有DataRows的填充的DataTable。
例如,如果要返回DataRows的序列化字符串,则需要将方法签名从DataTable更改为string或创建一个新方法。
public string ReturnSerialisedData()
{
// Add data table code here
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(rows);
}
另外,您可能希望将代码分成更多服务/数据访问层,而不是直接在Page_Load事件中执行数据库操作。