I want to add one row from dataset ds to dc every time. and I want to keep updating the Gridview to bigger the table. But when I try it in my code. the Gridview can only display one row according to what i input in the textbox.
public partial class TestGridview : System.Web.UI.Page
{
int count = 0;
DataSet dc = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
string text = TextBox1.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["XMLConnectionString"].ConnectionString);
// Create the command object
string str = "SELECT * FROM XML WHERE [Part_Numbber] = #textInput";
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.AddWithValue("textInput", text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "XML");
if (count == 0)
{
dc = ds.Clone();
count ++;
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i].ItemArray[0].ToString() != "NULL")
{
dc.Tables[0].ImportRow(ds.Tables[0].Rows[i]);
}
}
GridView1.DataSource = dc;
GridView1.DataBind();
}
}
You can make use of below code to append rows from 1 DT to other final DT. LikeWise
foreach (DataRow dataRow in dt2.Rows)
{
DataRow dr = dt1.NewRow();
dr[0] = Convert.ToInt32(dataRow[0]);
dr[1] = dataRow[1].ToString();
dr[2] = dataRow[2].ToString();
dt1.Rows.Add(dr);
}
foreach (DataRow dataRow in dt3.Rows)
{
DataRow dr = dt1.NewRow();
dr[0] = Convert.ToInt32(dataRow[0]);
dr[1] = dataRow[1].ToString();
dr[2] = dataRow[2].ToString();
dt1.Rows.Add(dr);
}
foreach (DataRow dataRow in dt4.Rows)
{
DataRow dr = dt1.NewRow();
dr[0] = Convert.ToInt32(dataRow[0]);
dr[1] = dataRow[1].ToString();
dr[2] = dataRow[2].ToString();
dt1.Rows.Add(dr);
}
Related
I need to add "Select" at index 0 without know DataTable columns count or name because this method in DataAccessLayer and will use later`
// ComboBox Fill Method
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
{
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
cbo.DataSource = dt;
cbo.DisplayMember = cboDisplayMember;
cbo.ValueMember = cboValueMember;
cbo.SelectedIndex = 0;
con.Close();
}
I have solved this issue by the following code.
Thanks for all ...
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
{
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
DataRow drow = dt.NewRow();
for (int i = 0; i < dt.Columns.Count ; i++)
{
if (dt.Columns[i].ColumnName == cboDisplayMember)
{
drow[i] = "Select";
}
else if (dt.Columns[i].ColumnName == cboValueMember)
{
drow[i] = 0;
}
else
{
drow[i] = null;
}
}
dt.Rows.InsertAt(drow, 0);
cbo.DataSource = dt;
cbo.DisplayMember = cboDisplayMember;
cbo.ValueMember = cboValueMember;
cbo.SelectedIndex = 0;
con.Close();
}
Just put this line in your ComboBoxFill() function.
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
{
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
cbo.DataSource = dt;
DataRow newRow = dt.NewRow();
newRow[0] = "Select";
dt.Rows.InsertAt(newRow, 0);
cbo.DisplayMember = cboDisplayMember;
cbo.ValueMember = cboValueMember;
cbo.SelectedIndex = 0;
con.Close();
}
It will add "Select" at postion 0
Here is full code at the moment what I have done. So basically I'm creating a DataTable, then I'm connecting my DataTable with a database. I can edit person by ID, but I don't know how to delete person by ID. I want a full row to be deleted.
As well, in the part where I edit the DataTable, if I choose not to edit table, I get some null reference error
Object reference not set to an instance of an object.
My code:
/*
* Creating DataTable
*/
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(int)));
dt.Columns.Add(new DataColumn("Vards", typeof(string)));
dt.Columns.Add(new DataColumn("Uzvards", typeof(string)));
/*
* Connecting to DataBase
*/
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"datubaze.accdb\"";
OleDbConnection con = new OleDbConnection(ConnectionString);
OleDbCommand cmd = new OleDbCommand("SELECT * FROM PERSONA", con);
con.Open();
OleDbDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
DataRow dr = dt.NewRow();
dr["ID"] = dataReader["ID"];
dr["Vards"] = dataReader["Vards"];
dr["Uzvards"] = dataReader["Uzvards"];
dt.Rows.Add(dr);
}
con.Close();
dt.AcceptChanges();
PrintDataTable(dt);
Console.WriteLine();
/* Edit Person in DataTable */
Console.WriteLine("Kuru ID vēlaties labot?");
int labosana = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Vai tiešām vēlaties labot šo ierakstu?");
string vaiLabot = Console.ReadLine();
if (vaiLabot == "yes")
{
Console.WriteLine("Ievadiet jauno vārdu:");
string vards = Console.ReadLine();
Console.WriteLine("Ievadiet jauno uzvārdu:");
string uzvards = Console.ReadLine();
dt.Rows[labosana-1]["Vards"] = vards;
dt.Rows[labosana-1]["Uzvards"] = uzvards;
}
else
{
Console.WriteLine("Jūs atteicāties labot!");
}
/*
* Adding Edited Person to Database
*/
OleDbCommand upCmd = new OleDbCommand("UPDATE PERSONA SET Vards=?,Uzvards=? WHERE ID=?", con);
upCmd.Parameters.Add(new OleDbParameter("#Vards",OleDbType.VarChar));
upCmd.Parameters.Add(new OleDbParameter("#Uzvards", OleDbType.VarChar));
upCmd.Parameters.Add(new OleDbParameter("#ID", OleDbType.Integer));
foreach(DataRow dro in dt.GetChanges().Rows)
{
if (dro.RowState == DataRowState.Modified)
{
upCmd.Parameters[0].Value = dro[1];
upCmd.Parameters[1].Value = dro[2];
upCmd.Parameters[2].Value = dro[0];
con.Open();
upCmd.ExecuteNonQuery();
con.Close();
}
}
I tried a ton of code. But none of them seems to work. Tried something like this to delete by the Name.
for(int i = dt.Rows.Count-1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
if (dr["Vards"] == "Name")
dr.Delete();
}
Use this code for deleting by Id from database:
public int DeleteById(int Id)
{
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"datubaze.accdb\"";
OleDbConnection con = new OleDbConnection(ConnectionString);
OleDbCommand cmd = new OleDbCommand("DELETE FROM PERSONA WHERE ID = #ID", con);
cmd.Parameters.Add(new OleDbParameter("ID", Id));
return cmd.ExecuteNonQuery();
}
Updated: try this -- To delete from the DataTable
DataRow rowToBeDeleted;
for(int i = dt.Rows.Count-1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
if (dr["Vards"] == "Name")
rowToBeDeleted = dr;
}
dt.Rows.Remove(rowToBeDeleted );
Or if using LINQ, you can also do something like
var dr = dt.AsEnumerable().Where(row => row.Field<string>("Vards") == "Name").SingleOrDefault();
dt.Rows.Remove(dr);
I tried create and fill a simple DataTable
Result of this code :
Order Driver
1
1
But I want to show on same row like this :
Order Driver
1 1
Where is my wrong in this code ?
public DataTable MethodName(string Param)
{
DataRow dr;
DataTable dt= new DataTable();
dt.Columns.Add("Order", Type.GetType("System.Int32"));
dt.Columns.Add("Driver", Type.GetType("System.Int32"));
if(AnotherMethod1(Param))
{ dr = dt.NewRow();
dr["Order"] = 1;
dt.Rows.Add(dr);
}
else
{ dr = dt.NewRow();
dr["Order"] = 0;
dt.Rows.Add(dr);
}
if(AnotherMethod2(Param))
{ dr = dt.NewRow();
dr["Driver"] = 1;
dt.Rows.Add(dr);
}
else
{ dr = dt.NewRow();
dr["Driver"] = 0;
dt.Rows.Add(dr);
}
return dt;
}
You're adding a row every time you set value to a different column.
Try this:
public DataTable MethodName(string Param)
{
DataTable dt = new DataTable();
dt.Columns.Add("Order", typeof(Int32));
dt.Columns.Add("Driver", typeof(Int32));
DataRow dr = dt.NewRow();
dr["Order"] = AnotherMethod1(Param) ? 1 : 0;
dr["Driver"] = AnotherMethod2(Param) ? 1 : 0;
dt.Rows.Add(dr);
return dt;
}
public DataTable MethodName(string Param)
{
DataRow dr;
DataTable dt= new DataTable();
dt.Columns.Add("Order", Type.GetType("System.Int32"));
dt.Columns.Add("Driver", Type.GetType("System.Int32"));
dr = dt.NewRow();
if(AnotherMethod1(Param))
{
dr["Order"] = 1;
}
else
{
dr["Order"] = 0;
}
if(AnotherMethod2(Param))
{
dr["Driver"] = 1;
}
else
{
dr["Driver"] = 0;
}
dt.Rows.Add(dr);
return dt;
}
I want to fill grid view with textbox and dropddown list values recursively on button click.Currently it is binding only once.I am new to ASP.NET.Help would be highly appreciated
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Resource");
dt.Columns.Add("available");
for (int intCnt = 0; intCnt < grd.Rows.Count - 1; intCnt++)
{
if (grd.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Resource"] = grd.Rows[intCnt].Cells[0];
dr["available"] = grd.Rows[intCnt].Cells[1];
dt.Rows.Add(dr);
}
}
dr = dt.NewRow();
dr["Resource"] = ddlResource.SelectedItem.Text;
dr["available"] = txtavailable.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}
Please try this hope it will help
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Resource");
dt.Columns.Add("available");
foreach(GridViewRow row in grd.Rows)
{
dr = dt.NewRow();
dr["Resource"] = row.Cells[0].Text;
dr["available"] =row.Cells[1].Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dr["Resource"] = ddlResource.SelectedItem.Text;
dr["available"] = txtavailable.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}
Use following code:
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = defineColumn();
DataRow dr;
foreach (GridViewRow grow in grdChMedicine.Rows)
{
dr = dt.NewRow();
dr["Diagnosis"] = grow.Cells[1].Text;
dr["DiagnosisId"] = grow.Cells[2].Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dr["Diagnosis"] = ddldiagnosis.SelectedItem.ToString();
dr["DiagnosisId"] = ddldiagnosis.SelectedValue;
dt.Rows.Add(dr);
ViewState["ChMedicine"] = dt;
grdChMedicine.DataSource = dt;
grdChMedicine.DataBind();
}
private DataTable defineColumn()
{
DataTable dt = new DataTable();
dc = new DataColumn("Diagnosis");
dt.Columns.Add(dc);
dc = new DataColumn("DiagnosisId");
dt.Columns.Add(dc);
return dt;
}
I am new in C#.I want to add rows in a GridView in runtime. I collect a data from 2 or 3 tables. But whenever I am going to
bind() it with GridView, the last inserted row is overwritten by current one. And GridView shows only the current row.
Is it possible to show both rows one bellow the other? Or Is there any code for doing so.Please suggest me code for that so that i can use it in my project.Thanks.
Answer::First you have to declare a static datatable.And a boolean variable having value initially "true".
And then execute following code--->>>
Here is My code::
protected void btnAdd_Click(object sender, EventArgs e)
{
int coursemasterid = Convert.ToInt32(dlAdmissionCourses.SelectedItem.Value);
int batchmasterid = Convert.ToInt32(dlAssignBatch.SelectedItem.Value);
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
DataTable otable = new DataTable();
otable = DbHelper.ExecuteTable(DbHelper.CONSTRING, CommandType.Text, SQL1, null);
DataRow dr1 = otable.Rows[0];
string coursename = dr1["coursename"].ToString();
int coursefees = Convert.ToInt32(dr1["coursefees"]);
string batchname = dr1["batchname"].ToString();
if (chkadd == true)
{
dtglb = new DataTable(); //here dtglb is a global datatable
dtglb.Columns.Add("coursename", typeof(string));
dtglb.Columns.Add("coursefees", typeof(int));
dtglb.Columns.Add("batchname", typeof(string));
}
foreach (DataRow dr in otable.Rows)
{
dtglb.NewRow();
dtglb.Rows.Add(coursename,coursefees,batchname);
}
chkadd = false;
GridView1.DataSource = dtglb;
GridView1.DataBind();
}
//declaring a datatable global in form
DataTable dtglb=new DataTable();
//In click event
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=EMS;User ID=sa;Password=sa123");
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
SqlCommand cmd = new SqlCommand(SQL1, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
//DataColumn faculty = new DataColumn();
da.Fill(ds);
GridView1.DataSourceID = null;
//New Code Added Here
DataRow row = ds.NewRow();
//your columns
row["columnOne"] = valueofone;
row["columnTwo"] = valueoftwo;
dtglb.Rows.Add(row);
foreach(DataRow dr in dtglb.Rows)
{
ds.Rows.Add(dr);
}
//=========
GridView1.DataSource = ds;
GridView1.DataBind();
add rows to DataGridView itself
DataGridViewRow row = new DataGridViewRow();
dataGridView1.BeginEdit();
//your columns
row.Cells["columnOne"] = valueofone;
row.Cells["columnTwo"] = valueoftwo;
dataGridView1.Rows.Add(row);
dataGridView1.EndEdit();