日期:2014-05-18  浏览次数:21026 次

c# 提示表没有主键
刚学c# 遇到这个问题搜都搜不到 希望各位路过的大虾能解答
using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.Odbc;
namespace Test
{
  public partial class Form1 : Form
  {
  public Form1()
  {
  InitializeComponent();
  }
OdbcConnection conn;
  DataSet ds;
OdbcDataAdapter sda;
  private void Form1_Load(object sender, EventArgs e)
  {
conn = new OdbcConnection("dsn=shushu");
OdbcCommand cmd = new OdbcCommand("select * from stu", conn);
sda = new OdbcDataAdapter();
  sda.SelectCommand = cmd;
  ds = new DataSet();
  sda.Fill(ds, "stu");
  dataGridView1.DataSource = ds.Tables[0];
  }
  private void button1_Click(object sender, EventArgs e)
  {
  DataTable dt = ds.Tables["stu"];
  sda.FillSchema(dt, SchemaType.Mapped);
DataRow dr = dt.Rows.Find(txtNo.Text); //提示没有主键
dr["sname"] = this.txtName.Text.Trim();
   
dr["grade"] = this.txtAge.Text.Trim();
   
OdbcCommandBuilder cmdbuider = new OdbcCommandBuilder(sda);
  sda.Update(dt);
  }
  private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
  {
  txtNo.Text = dataGridView1.SelectedCells[0].Value.ToString();
  txtName.Text = dataGridView1.SelectedCells[1].Value.ToString();
  txtgrade.Text = dataGridView1.SelectedCells[2].Value.ToString();
   
  }


  }
}





------解决方案--------------------
看看你建的表有没有主键嘛~最近也是正在学习c#,这么好的贴,可不能沉了啊!
------解决方案--------------------
[code=C#]
DataTable dt = GetDataSource();
dt.PrimaryKey=new DataColumn[] {dt.Columns[0]};//设置第一列为主键
DataRow row = dt.Rows.Find( "101 ");//获取DataTable中主键值为101的一行数据
JScript.Alert(this, row[0].ToString());//弹出获取行的第一列的值
[/code]