Table doesn't have a primary key - c#

i get the following exception (missing primary key) in the line of using Find() method
"Table doesn't have a primary key."
I've rechecked the Database and all Primary Key columns are set correctly.
my code:
DataTable dt = p.GetAllPhotos(int.Parse(Id));
DataTable temp = new DataTable();
temp = dt.Clone();
temp = (DataTable)(Session["currentImage"]);
DataTable dtvalid = new DataTable();
dtvalid = dt.Clone();
DataRow[] drr = new DataRow[1];
drr[0] = dt.Rows.Find((int.Parse(temp.Rows[0]["photoId"].ToString()))+1);
foreach (DataRow dr in drr)
{
dtvalid.ImportRow(dr);
}
dtvalid.AcceptChanges();'

You need to set the PrimaryKey property of your DataTable object before you call Find
DataColumn[] keyColumns = new DataColumn[1];
keyColumns[0] = dt.Columns["<columnname>"];
dt.PrimaryKey = keyColumns;

Related

How to add row with default values into System.Data.DataTable

I have DataTable and I need to add row with default values and save it into database.
BONUS: Would be awesome to auto increment key column.
How can I achieve that?
static int i = 1;
private void CreateDefault()
{
DataColumn column = null;
DataTable table = new DataTable();
column = new DataColumn();
var Col1 = column;
Col1.DataType = System.Type.GetType("System.Int32");
Col1.DefaultValue = i;
Col1.Unique = false;
table.Columns.Add(column);
i = i + 1;
column = new DataColumn();
var Col2 = column;
Col2.DataType = System.Type.GetType("System.String");
Col2.DefaultValue = "Your String";
table.Columns.Add(column);
DataRow row = null;
row = table.NewRow();
table.Rows.Add(row);
}
Variable i will be auto increment key column. Now Insert the DataTable to DataBase.
You can add a new row with default values and save it into database like this.
using (var conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM YourTableName", conn);
SqlDataAdapter da = new SqlDataAdapter() { SelectCommand = cmd };
// Load records to a DataSet
DataSet ds = new DataSet();
da.Fill(ds, "YourTableName");
var table = ds.Tables["YourTableName"];
// Add a new row with default value
table.Rows.Add();
// Reflect the change to database
SqlCommandBuilder cb = new SqlCommandBuilder(da);
da.Update(ds, "YourTableName");
}
Also, if you've set an auto increment key like IDENTITY for MS SQL Server (https://msdn.microsoft.com/en-us/library/ms186775.aspx), this works when the new row is inserted.

how to display records based on one column from table in c#?

it displays error : table does not have primary key
DataSet ds = new DataSet("ds1");
DataTable dt = ds.Tables.Add("tblcategory");
string s = textBox1.Text.ToString();
DataRow foundRow = ds.Tables["tblcategory"].Rows.Find(s);
if (foundRow != null)
{
MessageBox.Show(foundRow[0].ToString());
}
You have to set table structure and, in particular, primary key column(s), to be able to find rows with Find, e.g.:
var column = dt.Columns.Add("Id", typeof(int));
column.AllowDBNull = false;
column.Unique = true;

How i can read xml into DataTable type object?

I don't have problem if i read xml to DataSet:
DataSet temp = new DataSet();
temp.ReadXml(UncompressedStream, System.Data.XmlReadMode.Auto);
But if i use DataTable:
DataTable temp = new DataTable();
temp.ReadXml(UncompressedStream);
then datatable not load data (count of columns and rows equal 0 )
How i can read xml to DataTable
My temporary solution:
DataSet temp = new DataSet();
DataTable structure = new DataTable();
temp.ReadXml(UncompressedStream, System.Data.XmlReadMode.Auto);
structure = temp.Tables[0];
private static void DemonstrateReadWriteXMLDocumentWithString()
{
DataTable table = CreateTestTable("XmlDemo");
PrintValues(table, "Original table");
string fileName = "C:\\TestData.xml";
table.WriteXml(fileName, XmlWriteMode.WriteSchema);
DataTable newTable = new DataTable();
newTable.ReadXml(fileName);
// Print out values in the table.
PrintValues(newTable, "New table");
}
private static DataTable CreateTestTable(string tableName)
{
// Create a test DataTable with two columns and a few rows.
DataTable table = new DataTable(tableName);
DataColumn column = new DataColumn("id", typeof(System.Int32));
column.AutoIncrement = true;
table.Columns.Add(column);
column = new DataColumn("item", typeof(System.String));
table.Columns.Add(column);
// Add ten rows.
DataRow row;
for (int i = 0; i <= 9; i++)
{
row = table.NewRow();
row["item"] = "item " + i;
table.Rows.Add(row);
}
table.AcceptChanges();
return table;
}
This is from: microsoft - xml - datatable
Check that in this code, they add a name for the table, and create the rows and the columns.
LINQ to XML may be a thing you are rather looking for.

Unable to import or add row from a datatable

I am trying to add a row acquired from a database to a DataTable.
First I tried Using bucketdt.Rows.Add(r); I got an error saying Row belongs to another Table
Then I used bucketdt.ImportRow(r); then it doesn't copy the row at all!
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
//DataTable f = new DataTable();
dosObject = new DataOperations();
bucketdt = new DataTable();
count=0;
foreach (string key in Session.Keys)
{
string val = Session[key].ToString();
DataRow r = bucketdt.NewRow();
r = dosObject.SubCategoryDetails2(Convert.ToInt16(val)).Rows[0];
bucketdt.ImportRow(r);
bucketdt.AcceptChanges();
}
GridView1.Enabled = true;
GridView1.DataSource = bucketdt;
GridView1.DataBind();
}
else
Response.Redirect(FormsAuthentication.LoginUrl);
am I missing something?
Now I tried adapting the code as told by #wonko79
DataTable f = new DataTable();
dosObject = new DataOperations();
bucketdt = new DataTable();
count=0;
foreach (string key in Session.Keys)
{
string val = Session[key].ToString();
DataRow r = bucketdt.NewRow();
f = dosObject.SubCategoryDetails2(Convert.ToInt16(val));
r["Id"]=f.Rows[0].ItemArray[0].ToString();
r["SubCategoryName"] = f.Rows[0].ItemArray[1].ToString();
r["Make"] = f.Rows[0].ItemArray[2].ToString();
r["Cost"] = f.Rows[0].ItemArray[3].ToString();
//bucketdt.ImportRow(r);
bucketdt.Rows.Add(r);
bucketdt.AcceptChanges();
n now it says the row doesnt contain Column: 'Id' does not belong to table .
You are overwriting your DataRow r which follows the schema of bucketdt with a DataRow folowing another schema.
DataRow r = bucketdt.NewRow();
r = dosObject.SubCategoryDetails2(Convert.ToInt16(val)).Rows[0]; // overwrites r with a DataRow following another schema

Getting value from a DataSet into a variable

I have the following method which returns dataset. I am using .NET 2.0
DataSet ds = GetAllRecords();
I want to get values from each column for a particular row and bind it to a variable.
How can this be achieved?
currently the method returns all the row from the table and I have to find that particular row based on ID.
However, if that is not possible I can come with
DataSet ds = GetSpecificRecord(id);
But I still need to get values from each column and bind it to variable.
Please advice.
// Create a table
DataTable table = new DataTable("users");
table.Columns.Add(new DataColumn("Id", typeof(int)));
table.Columns.Add(new DataColumn("Name", typeof(string)));
table.Rows.Add(1, "abc");
table.Rows.Add(2, "ddd");
table.Rows.Add(3, "fff");
table.Rows.Add(4, "hhh d");
table.Rows.Add(5, "hkf ds");
// Search for given id e.g here 1
DataRow[] result = table.Select("Id = 1"); // this will return one row for above data
foreach (DataRow row in result)
{
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
This will get you the value from Row 0 obviously you would need to modify for multiple rows returned
long id = ds.Tables[0].Rows[0].Field<long>("ID");
You can do this with LINQ.
DataRow resultRow = ds.Tables["SomeTable"].AsEnumerable().Where(row => row.Field<int>("SomeID") == 1).FirstOrDefault();
For .NET 2.0 and below
If your DataTable has a primary key defined, you can find the row like this:
DataTable table = ds.Tables["SomeTable"];
DataRow row = table.Rows.Find(1);
If there is no primary key, you can assign one like this:
DataTable table = ds.Tables["SomeTable"];
table.PrimaryKey = new DataColumn[] { table.Columns["SomeID"] };
DataRow row = table.Rows.Find(1);
Another option is to use the RowFilter property of the DefaultView, like this:
DataTable table = ds.Tables["SomeTable"];
table.DefaultView.RowFilter = "SomeID == 1"; //not sure if it's == or = here
DataRow row = table.DefaultView[0].Row;
Lastly, you can also use the DataTable.Select() method to find rows.
Have you looked at using a typed dataset? If you're looking for a row based on the primary key of a table it will autogenerate a method for you to get a row by ID and it will be strongly typed so you can get column values by name.
They were quite handy in .Net 2.0 - but LINQ made them fairly obsolete.
Edit: A slightly better reference URL
http://www.c-sharpcorner.com/UploadFile/rupadhyaya/TypedDataSets12032005021013AM/TypedDataSets.aspx
We can get value from dataset by using this easy method:
System.Data.DataSet ds = db.MySelect(
"Fields",
"Table",
"Condition"
);
if (ds != null)
{
if (ds.Tables[0].Rows.Count > 0)
{
object value=Tables[0].Rows[indx]["field name"];
}
}
To fetch values from student table and display it in console window.
class Class1
{
static void Main(string[] args)
{
SqlConnection con=new SqlConnection(<connectionstring>);
SqlCommand cmd = new SqlCommand("select * from Student", con);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds=new DataSet();
ad.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
try
{
DataRow r = ds.Tables[0].Rows[i];
Console.WriteLine(r.Field<Int32>(0));
Console.WriteLine(r.Field<String>(1));
Console.WriteLine(r.Field<String>(2));
Console.WriteLine(r.Field<Decimal>(3));
Console.WriteLine(r.Field<Int16>(4));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Console.ReadKey();
}
}
sql Student table Info
Id int
Name varchar(50)
EmailId nvarchar(50)
MobileNo numeric(10,0)
Standard smallint

Categories

Resources