我需要一些帮助,了解如何实现在MS SQL中插入外键值,同时在同一个aspx页面中将结果绑定到gridview中。
我的代码在Build Solution上运行正常并且没有错误,但它在浏览器中显示以下行错误。
行:940错误:Sys.WebForms.PageRequestManagerServerErrorException: 名称为' TypeName'的字段或媒体资源没找到了 选定的数据来源。
我正在使用MS SQL 2008& MS Visual Studio 2013
以下是我项目中的代码
ASPX Gridview:
<!-- Main Gridview -->
<asp:GridView ID="gvItemgrid" runat="server" AutoGenerateColumns="false" DataKeyNames="ItemID"
ShowHeader="false" CssClass="Grid">
<RowStyle Wrap="false" CssClass="row" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgbtn" ImageUrl="../images/Edit.jpg" runat="server" Width="12px" Height="12px" OnClick="imgbtn_Click" /></ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="50px" DataField="ItemID" HeaderText="ItemID" />
<asp:BoundField ItemStyle-Width="500px" DataField="ItemName" HeaderText="ItemName" />
<asp:BoundField ItemStyle-Width="500px" DataField="TypeName" HeaderText="TypeName" />
</Columns>
</asp:GridView>
C#代码:
// C# Code
#region BindTypeList (ddlType)
// bind the Type list in drop down list..
private void BindTypeList(DropDownList ddlType)
{
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("select * from inv_TypeList");
cmd.Connection = con;
con.Open();
this.ddlType.DataSource = cmd.ExecuteReader();
this.ddlType.DataTextField = "TypeName";
this.ddlType.DataValueField = "TypeID";
this.ddlType.DataBind();
con.Close();
}
#endregion
//button save
#region btnSave
protected void btnSave_Click(object sender, EventArgs e)
{
//Calling the database for Insert Statement
SqlConnection con = new SqlConnection(strConnString);
// call stored procedure
SqlCommand cmd = new SqlCommand("inv_ItemList_Insert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
// add values
cmd.Parameters.AddWithValue("@ItemName", txtItemName.Text);
cmd.Parameters["@ItemName"].Value = txtItemName.Text;
cmd.Parameters.AddWithValue("@TypeID", ddlType.SelectedItem.Value);
cmd.Parameters["@TypeID"].Value = ddlType.SelectedItem.Value;
// add the result
cmd.Parameters.Add(new SqlParameter("@Result", SqlDbType.VarChar, 1000));
cmd.Parameters["@Result"].Direction = ParameterDirection.Output;
try
{
// open the database..
con.Open();
cmd.ExecuteNonQuery();
// perform some actions here..
//btnSave.Enabled = false;
string result = cmd.Parameters["@Result"].Value.ToString();
// label notification..
lblMsg.Visible = false;
lblMsg.Text = result;
BindGrid();
// if meets condition to perform some actions..
if ((lblMsg.Text == ("Item Name: " + (txtItemName.Text + (" " + "already exists..")))))
{
// controls set to active..
txtItemName.Enabled = true;
ddlType.Enabled = true;
//txtRegister.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
txtItemName.Focus();
// lblMsg notification display
lblMsg.Attributes.Add("style", "color: #FFFFFF");
lblMsg.Attributes.Add("style", "background-color: OrangeRed");
lblMsg.Visible = false;
btnNew.Enabled = false;
// javascript messagebox "IP Address exist!"
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "msgExist", "msgExist();", true);
}
else
{
//Method in displaying data in reverse (last - first)
//Calling the database
SqlConnection con2 = new SqlConnection(strConnString);
string strConString = "select * from inv_ItemList order by ItemID DESC";
SqlCommand cmd2 = new SqlCommand(strConString);
gvItemgrid.DataSource = GetData(strConString);
gvItemgrid.DataBind();
//Highlighting the first row in gridview
object firstRowIndex = gvItemgrid.Rows[0];
gvItemgrid.Rows[0].BackColor = System.Drawing.Color.LemonChiffon;
//Display records
//current record per page
int val1 = Convert.ToInt32(gvItemgrid.Rows.Count.ToString());
int val2 = Convert.ToInt32(lblcurrentpage.Text.ToString());
int val3 = val1 * val2;
lblrecperpage.Text = Convert.ToString(val3);
//display page
lbltotalpage.Text = lblcurrentpage.Text;
//paging function disabled..
btnFirst.Enabled = false;
btnNext.Enabled = false;
btnPrevious.Enabled = false;
btnLast.Enabled = false;
//controls set to disabled
txtItemName.Enabled = false;
btnSave.Enabled = false;
////current date and time
//txtRegister.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
// lblMsg notification display
lblMsg.Attributes.Add("style", "color:#FFFFFF");
lblMsg.Attributes.Add("style", "background-color:Green");
// javascript messagebox "Data successfully saved"
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "msgSave", "msgSave();", true);
}
}
//catching internal error
catch (SqlException ex)
{
// throw some internal error in case there is
string errorMessage = "Error in registring user";
errorMessage = (errorMessage + ex.Message);
throw new Exception(errorMessage);
}
finally
{
//close the database..
con.Close();
}
// button new enabled..
btnNew.Enabled = true;
}
#endregion
// bind grid..
#region BindGrid
private void BindGrid()
{
// Call the Database & Stored Procedure for total Records
SqlConnection myConnection = new SqlConnection(strConnString);
SqlCommand myCommand = new SqlCommand("inv_ItemList_BindGrid", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("@startRowIndex", currentPageNumber);
myCommand.Parameters.AddWithValue("@maximumRows", PAGE_SIZE);
myCommand.Parameters.Add("@totalRows", SqlDbType.Int, 4);
myCommand.Parameters["@totalRows"].Direction = ParameterDirection.Output;
myCommand.Parameters.Add("@totalRec", SqlDbType.Int, 4);
myCommand.Parameters["@totalRec"].Direction = ParameterDirection.Output;
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
ad.Fill(ds);
gvItemgrid.DataSource = ds;
gvItemgrid.DataBind();
// Display the total records & pages..
double totalRows = int.Parse(myCommand.Parameters["@totalRows"].Value.ToString());
double totalRec = int.Parse(myCommand.Parameters["@totalRec"].Value.ToString());
lbltotalrec.Text = CalculateTotalRow(totalRec).ToString();
lbltotalpage.Text = CalculateTotalPages(totalRows).ToString();
// current page value
lblcurrentpage.Text = currentPageNumber.ToString();
// conditional meets
if ((currentPageNumber == 1))
{
// button first & prev disabled..
btnFirst.Enabled = false;
btnPrevious.Enabled = false;
if ((Int32.Parse(lbltotalpage.Text.ToString()) > 0))
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
else
{
btnNext.Enabled = false;
}
}
else
{
btnPrevious.Enabled = true;
btnFirst.Enabled = true;
if ((currentPageNumber == Int32.Parse(lbltotalpage.Text.ToString())))
{
btnNext.Enabled = false;
btnLast.Enabled = false;
}
else
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
}
//current record per page
int val1 = Convert.ToInt32(gvItemgrid.Rows.Count.ToString());
int val2 = Convert.ToInt32(lblcurrentpage.Text.ToString());
int val3 = val1 * val2;
lblrecperpage.Text = Convert.ToString(val3);
// conditional meets equalize the last page value & records..
if ((btnLast.Enabled == false))
{
lblrecperpage.Text = "";
lblrecperpage.Text = totalRec.ToString();
}
else
{
// point out the record at the end of the page..
lblrecperpage.Text = Convert.ToString(val3);
}
// condition
if ((lblrecperpage.Text == lbltotalrec.Text))
{
btnNext.Enabled = false;
btnLast.Enabled = false;
}
else
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
}
#endregion
SQL存储过程:inv_ItemList_Insert
ALTER PROCEDURE [dbo].[inv_ItemList_Insert]
-- Add the parameters for the stored procedure here
@ItemName VARCHAR(50),
@TypeID INT,
@Result VARCHAR (1000) OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF EXISTS (SELECT ItemName FROM dbo.inv_ItemList WHERE ItemName = RTRIM(@ItemName))
BEGIN
SET @Result = 'Item Name: '+ LTRIM(RTRIM(@ItemName)) + ' ' + 'already exists..'
END
ELSE
BEGIN
INSERT INTO [inv_ItemList] ([ItemName], [TypeID])
VALUES (@ItemName, @TypeID);
SET @Result = 'Item Name: '+ LTRIM(RTRIM(@ItemName)) + ' ' + 'is successfully added..'
End
END
SQL存储过程:inv_ItemList_BindGrid
ALTER PROCEDURE [dbo].[inv_ItemList_BindGrid]
-- Add the parameters for the stored procedure here
@startRowIndex int,
@maximumRows int,
@totalRows int OUTPUT,
@totalRec int OUTPUT
AS
DECLARE @first_id int, @startRow int
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SET @startRowIndex = ((@startRowIndex - 1) * @maximumRows) + 1
IF @startRowIndex = 0
SET @startRowIndex = 1
SET ROWCOUNT @startRowIndex
-- Insert statements for procedure here
SELECT @first_id = ItemID FROM inv_ItemList ORDER BY ItemID
PRINT @first_id
SET ROWCOUNT @maximumRows
SELECT ItemID, ItemName, inv_TypeList.TypeName FROM inv_ItemList
inner join inv_TypeList on inv_ItemList.TypeID=inv_TypeList.TypeID
WHERE
ItemID >= @first_id
ORDER BY ItemID
SET ROWCOUNT 0
-- GEt the total rows
SELECT @totalRows = COUNT(ItemID) FROM inv_ItemList
SELECT @totalRec = COUNT(*) FROM inv_ItemList
END
我的代码中是否有任何遗漏或任何其他方式来达到我的要求。
提前感谢您的帮助!
答案 0 :(得分:0)
我已经对我的代码进行了故障排除,并且发现了错误发生的位置。
我在SAVE按钮中修改了以下SQL语句
//Method in displaying data in reverse (last - first)
//Calling the database
SqlConnection con2 = new SqlConnection(strConnString);
string strConString = "select * from inv_ItemList order by ItemID DESC";
这一个
string strConString = "SELECT ItemID, ItemName, inv_TypeList.TypeName FROM inv_ItemList inner join inv_TypeList on inv_ItemList.TypeID=inv_TypeList.TypeID order by ItemID DESC";
错误不再显示,这就是解决错误的地方。 谢谢你们的帮助!:)