簡體   English   中英

無法將類型'object'隱式轉換為'string'。 存在顯式轉換(您是否缺少演員表?)

[英]Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

選擇下拉列表時,我必須在文本框中顯示值。 我已使用數據集從db獲取值。 代碼如下。 給我一個適當的解決方案。 謝謝。

碼:

 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
     {
        DataSet1TableAdapters.TextBoxTableTableAdapter tx;
        tx = new DataSet1TableAdapters.TextBoxTableTableAdapter();
        DataTable dt = new DataTable();
        dt = tx.GetstudData(int.Parse(DropDownList1.SelectedValue));
        foreach (DataRow row in dt.Rows)
           {
           TextBox1.Text = (row["FirstName"]); // error shown here
           TextBox2.Text = (row["SecondName"]); // error shown here
           }
     }

dt包含名字和姓氏值。 選擇學生ID時,應在文本框1和文本框2中顯示適當的值。

SQL查詢:

SELECT FirstName, SecondName FROM TextBoxTable WHERE (Id = @Id)

資源:

<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</div>

資料庫:

在此處輸入圖片說明

您可能想做:

foreach (DataRow row in dt.Rows)
{

 TextBox1.Text = (row["FirstName"]);
 TextBox2.Text = (row["SecondName"]);
}

將您的代碼更改為:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
     {
        DataSet1TableAdapters.TextBoxTableTableAdapter tx;
        tx = new DataSet1TableAdapters.TextBoxTableTableAdapter();
        DataTable dt = new DataTable();
        dt = tx.GetstudData(int.Parse(DropDownList1.SelectedValue));
        foreach (DataRow row in dt.Rows)
           {
           TextBox1.Text = (row["FirstName"].ToString());
           TextBox2.Text = (row["SecondName"].ToString());
           }
     }

文本框的名稱與asp文件中的名稱不同。 C#是區分大小寫的語言。

編輯:您必須將其轉換。 一個簡單的.ToString()應該做到這一點。 盡量不要更改主題的完整主題。 您應該打開一個新問題...因為這會打斷所有正確答案。

studentId是唯一的。 DownDropList包含Studentid。 一個學生有一個名字

if(DropDownList1.SelectedValue !="" && dt.Rows.Count()>0)
   {
       txtFirstname.Text= String.IsNullOrWhiteSpace(dt.Rows[0]["FirstName"]) ? "" : dt.Rows[0]["FirstName"];
     txtlastName.Text= String.IsNullOrWhiteSpace(dt.Rows[0]["LastName"]) ? "" : dt.Rows[0]["LastName"];      
}
 else
 {
   TextBox1.Text="";
  TextBox2.Text="";
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM