how to assign values to DataKeyNames in gridview programatically using C# - c#

I have a GridView. I am adding columns in it through c# in GridView gvExemptSub and retrieving data from another GridView gvSubj on button click. I want to assign data row values to DataKeyNames which I am retrieving from another GridView but I don't know how.
<asp:GridView ID="gvExemptSub" runat="server" Width="100%" DataKeyNames="LID,BID">
<Columns>
</Columns>
</asp:GridView>
protected void BtnAddSubj_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.TableName = "ExemptSubj";
dt.Columns.Add("QUALIFICATION", typeof(string));
dt.Columns.Add("SUBJECT", typeof(string));
dt.Columns.Add("LEVEL", typeof(string));
dt.Columns.Add("UNIVERSITY", typeof(string));
DataRow dr;
foreach (GridViewRow srow in gvSubj.Rows)
{
if (srow.RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr[0] = ddlQualification.SelectedItem;
string SUBJECT = srow.Cells[1].Text;
SUBJECT = SUBJECT.Replace("amp;", "");
dr[1] = SUBJECT;
dr[4] = int.Parse(gvSubj.DataKeys[srow.RowIndex]["LEVEL_ID"].ToString());
dr[2] = srow.Cells[2].Text;
dr[3] = ddlUNI.SelectedItem.Text;
dr[5] = ddlUNI.SelectedValue;
dt.Rows.Add(dr);
}
}
ViewState["ExemptSubj"] = dt;
//gvExemptSubj.DataKeyNames = (dr[4], dr[5])
gvExemptSubj.DataSource = dt;
gvExemptSubj.DataBind();
}

You can bind them programmatically with an string array:
GridView1.DataKeyNames = new string[2] { "ColumnA", "ColumnB" };

Related

asp.net grid view data binding without database

I am a beginner in asp.net and c#. I want to bind image and name to gridview without any database by hardcoding them in code behind.
I tried like below but these values are not binded to Gridview1. Can anyone tell me where it goes wrong?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="Profile_Name" HeaderText="Profile_Name" />
<asp:BoundField DataField="ImageUrl" HeaderText="ImageUrl" />
</Columns>
protected GridView GridView1;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.loadTable();
}
}
private void loadTable()
{
DataSet ds = new DataSet();
DataTable dt;
DataRow dr;
DataColumn pName;
DataColumn pImage;
dt = new DataTable();
pName = new DataColumn("Profile_Name", Type.GetType("System.String"));
pImage= new DataColumn("ImageURL", Type.GetType("System.String"));
dt.Columns.Add(pName);
dt.Columns.Add(pImage);
dr = dt.NewRow();
dr["Profile_Name"] = "John Cena";
dr["ImageUrl"] = "C:\\Users\\Desktop\\src\\Project\\Project.Web.WebForms\\Content\\Images\\Friends-PNG-Photos.png";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Profile_Name"] = "Hannah Ray";
dr["ImageUrl"] = "C:\\Users\\Desktop\\src\\Project\\Project.Web.WebForms\\Content\\Images\\Image.png";
dt.Rows.Add(dr);
ds.Tables.Add(dt);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
In the background you can make a new DataTable:
DataTable dt = new DataTable();
Then you can add data columns and rows through the dt.Rows and dt.Columns methods, and then set:
DataGridView.ItemsSource = dt.defaultview;
Hope that you find this helpful.
You can bind all objects to a DataGrid:
datagrid.DataSource = object;
datagrid.DataBind();

Adding rows to gridView

I want to add new rows after the inserted rows. I have a button that shows bootstrap modal with some DropDownLists and Textboxes. The button in modal on click should insert the data from modal to the table. The problem is that when i try to add new row it will replace current row. What im doing wrong? Here is sample of my code:
.cs:
protected void addTrip_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dostawca = DropDownDostawca.SelectedValue.ToString();
cel = txtCel.InnerText;
krajZagr = "";
kraj = DropDownKraj.SelectedValue.ToString();
miasto = txtMiasto.Text;
if(rbKraj.Checked == true)
{
krajZagr = "Krajowa";
}
if(rbZag.Checked == true)
{
krajZagr = "Zagraniczna";
}
if(cel=="" || miasto=="" || kraj=="" || dostawca=="" )
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "ShowPopup2();", true);
}
else
{
if(gridViewTrips.Columns.Count == 0)
{
DataRow dr = dt.NewRow();
DataColumn dc = new DataColumn("DO_KOGO");
DataColumn dc2 = new DataColumn("CEL");
DataColumn dc3 = new DataColumn("KRAJOWA_ZAGRANICZNA");
DataColumn dc4 = new DataColumn("KRAJ");
DataColumn dc5 = new DataColumn("MIASTO");
dt.Columns.Add(dc);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
dt.Columns.Add(dc5);
dr["DO_KOGO"] = dostawca;
dr["CEL"] = cel;
dr["KRAJOWA_ZAGRANICZNA"] = krajZagr;
dr["KRAJ"] = kraj;
dr["MIASTO"] = miasto;
dt.Rows.Add(dr);
gridViewTrips.DataSource = dt;
gridViewTrips.DataBind();
}
else
{
DataRow dr = dt.NewRow();
dr["DO_KOGO"] = dostawca;
dr["CEL"] = cel;
dr["KRAJOWA_ZAGRANICZNA"] = krajZagr;
dr["KRAJ"] = kraj;
dr["MIASTO"] = miasto;
dt.Rows.Add(dr);
gridViewTrips.DataSource = dt;
gridViewTrips.DataBind();
}
}
}
.aspx:
<asp:GridView runat="server" id="gridViewTrips">
<EmptyDataTemplate>
<asp:Table ID="TableTrips" runat="server" CssClass="table table-bordered">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Do kogo</asp:TableHeaderCell>
<asp:TableHeaderCell>Cel</asp:TableHeaderCell>
<asp:TableHeaderCell>Krajowa/Zagraniczna</asp:TableHeaderCell>
<asp:TableHeaderCell>Kraj</asp:TableHeaderCell>
<asp:TableHeaderCell>Miasto</asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
</EmptyDataTemplate>
</asp:GridView>
EDIT: Now I see when I debug my project the IF what i have: "if(gridViewTrips.Columns.Count == 0)" after inserted one row shows me that I dont have any columns. Any ideas what is going on?
What about create GridView column first...
https://msdn.microsoft.com/en-us/library/system.windows.controls.gridviewcolumn(v=vs.110).aspx
and then AddChild method?
https://msdn.microsoft.com/en-us/library/system.windows.controls.gridview(v=vs.110).aspx

how to delete from gridview without database "check to determine if the object is null before calling the method"

The ff are codes in my .cs file
private void BindGridview(int rowcount)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("Code", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Course", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Credit", typeof(String)));
if (ViewState["CurrentData"] != null)
{
for (int i = 0; i < rowcount + 1; i++)
{
dt = (DataTable)ViewState["CurrentData"];
if (dt.Rows.Count > 0)
{
dr = dt.NewRow();
dr[0] = dt.Rows[0][0].ToString();
}
}
dr = dt.NewRow();
dr[0] = this.cboCourseCode.Text;
dr[1] = this.txtCourseName.Text;
dr[2] = this.txtCredit.Text;
dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr[0] = this.cboCourseCode.Text;
dr[1] = this.txtCourseName.Text;
dr[2] = this.txtCredit.Text;
dt.Rows.Add(dr);
}
// If ViewState has a data then use the value as the DataSource
if (ViewState["CurrentData"] != null)
{
GridView1.DataSource = (DataTable)ViewState["CurrentData"];
GridView1.DataBind();
}
else
{
// Bind GridView with the initial data assocaited in the DataTable
GridView1.DataSource = dt;
GridView1.DataBind();
}
// Store the DataTable in ViewState to retain the values
ViewState["CurrentData"] = dt;
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[e.RowIndex].Delete();
ViewState["dt"] = dt;
BindGrid();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string Code = e.Row.Cells[0].Text;
foreach (Button button in e.Row.Cells[3].Controls.OfType<Button>())
{
if (button.CommandName == "Delete")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + Code + "?')){ return false; };";
}
}
}
}
protected void cboCourseCode_SelectedIndexChanged(object sender, EventArgs e)
{
this.Populate_Course_Details();
}
protected void BtnAdd_Click(object sender, EventArgs e)
{
/* DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Code"), new DataColumn("Course"), new DataColumn("Credit") });
dt.Rows.Add(this.cboCourseCode.Text, this.txtCourseName.Text, this.txtCredit.Text);
ViewState["dt"] = dt;
BindGrid();*/
if (ViewState["CurrentData"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentData"];
int count = dt.Rows.Count;
BindGridview(count);
}
else
{
BindGridview(1);
}
}
My aspx file also has this gridview
<asp:GridView ID="GridView1" CssClass = "Grid" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns = "false" OnRowDataBound = "OnRowDataBound">
<Columns>
<asp:BoundField DataField="Code" HeaderText="Code" />
<asp:BoundField DataField="Course" HeaderText="Course" />
<asp:BoundField DataField="Credit" HeaderText="Credit" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
When I start to delete, I get this error:
check to determine if the object is null before calling the method
Error Reason
in OnRowDeleting function you are creating datatable and assigning viewstate["dt"],which doesn't have current data. that's why it shows Object is Null
Solution
Try This
First make one of the column as data key.consider i want to make "Code" column as datakey.
datakey will help to find specific row to delete
<asp:GridView ID="GridView1" CssClass = "Grid" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns = "false" OnRowDataBound = "OnRowDataBound" DataKeyNames="Code">
After That in .cs code
create a datatable with currentdata
make "Code" column as primary key
find particular code(which you want to delete)using find()
then delete that row using delete() function
Reflect the deletion in viewsate["currentdata"]
then bind to gridview
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
string code = GridView1.DataKeys[e.RowIndex].Value.ToString();
if (ViewState["CurrentData"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentData"];
dt.PrimaryKey = new DataColumn[] { dt.Columns["Code"] };
dt.Rows.Find(code).Delete();
ViewState["CurrentData"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}

DataTable row filling in C#

I am trying to add row in DataTable CartDT using row[], which is a string array.
DataTable CartDT = new DataTable();
public void DataTableColumn()
{
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
}
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity = (TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
string[] row = new string[5];
row[0] = arg[0]; //Product_Name
row[1] = arg[1]; //Product_ID
row[2] = itemQuantity.Text; //OrderQTY
row[3] = arg[2]; //Price
row[4]=(Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString();// calculate total price
CartDT.Rows.Add(row);//Creating row in Datatable using row[] string array
GridView2.DataSource = CartDT;
GridView2.DataBind();
}
Now when I execute it, it gives the error that "Input array is longer than the number of columns in this table"
The array row[] has exactly 5 elements in it & also DataTable CartDT has also 5 columns.
Now i am not able to find exactly where i am wrong.
Please help me to find the bug.
Thanx in advance.
Instead do this
DataRow dr = CartDT.NewRow();
Then
dr[0] = arg[0];
and so on. In the end
CartDT.Rows.Add(dr);
CartDT.AcceptChanges();
This way the instance of Row will have CartDT schema.
DataTable CartDT = new DataTable();
public void CreateDataTableColumns()
{
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
}
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
if (CartDT.Columns.Count = 0)
{
CreateDataTableColumns();
}
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity =
(TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
DataRow dr = CartDT.NewRow();
dr[0] = arg[0]; //Product_Name
dr[1] = arg[1]; //Product_ID
dr[2] = itemQuantity.Text; //OrderQTY
dr[3] = arg[2]; //Price
dr[4] = (Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString(); // calculate total price
CartDT.Rows.Add(dr);
CartDT.AcceptChanges();
GridView2.DataSource = CartDT;
GridView2.DataBind();
}
Debug, and break on
CartDT.Rows.Add(row);
and see how many columns are in CartDT; I think you don't call DataTableColumn() at the right time.
Your code having to do with row insertion works just fine
DataTable CartDT = new DataTable();
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
string[] row = new string[5];
row[0] = "1"; //Product_Name
row[1] = "2"; //Product_ID
row[2] = "3"; //OrderQTY
row[3] = "4"; //Price
row[4] = "5";// calculate total price
CartDT.Rows.Add(row);//Creating row in Datatable using row[] string array
for (int i = 0; i < 5; i++)
{
Console.WriteLine(CartDT.Rows[0][i]);
}
Console.Read();
Try Below Code:
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity = (TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
DataRow row = CartDT.NewRow();
row["Product_Name"] = arg[0]; //Product_Name
row["Product_ID"] = arg[1]; //Product_ID
row["OrderQTY"] = itemQuantity.Text; //OrderQTY
row["Price"] = arg[2]; //Price
row["TotalPrice"]=(Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString();
CartDt.Rows.Add(row);
CartDT.AcceptChanges();
GridView2.DataSource = CartDT;
GridView2.DataBind();
}

Filling DataTable from GridView in C#

How can I fill DataTable from GridView in ASP.NET?
Simply, you can do like this:
BindingSource bindingSource = (BindingSource )yourGridView.DataSource;
DataTable yourDataTable= (DataTable ) bindingSource .DataSource;
Another way, you can do like this:
DataTable yourDataTable = yourGridView.DataSource as DataTable
I solved like this
if (myGridView.Rows.Count > 0)
{
var dt = new DataTable();
dt.Columns.Add("Column1", typeof(string));
dt.Columns.Add("Column2", typeof(Int64));
dt.Columns.Add("Column3", typeof(string));
foreach (GridViewRow row in gd_endYearSchool.Rows)
{
var id = row.Cells[1].Text;
//for find textbox
var tb1 = row.Cells[2].FindControl("tbNr") as TextBox;
int nrord = 0;
if (tb1 != null)
{
var ord = tb1.Text;
if (!Int64.TryParse(ord, out nrord))
{
nrord = 0;
}
}
var text=row.Cell[3].text;
dt.Rows.Add(id,nrord,text);
}
}
you can fill datatable from gridview with foreach
I'll do like this, i think this'll help u.
public void Data_table()
{
Session["Data"] = "";
DataTable dt = new DataTable();
//Add Columns to the datatable
dt.Columns.Add("c1");
dt.Columns.Add("c2");
dt.Columns.Add("c3");
//Define a datarow for the datatable dt
DataRow dr = dt.NewRow();
//Now add the datarow to the datatable
Session["Data"] = dt;
RadGrid1.DataSource = dt;
RadGrid1.Rebind();
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
if (((System.Data.DataTable)(Session["Data"])).Rows.Count.ToString() != "")
{
RadGrid1.DataSource = Session["Data"];
}
}
Thank you..,

Categories