I am copying the selcted data from on grid to another on the click of a button. I am using postgre SQl for my apllication. Here is the link for the
HTML. I am binding the data in as
NpgsqlDataAdapter adp;
NpgsqlConnection conn = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["projop"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPrimaryGrid();
BindSecondaryGrid();
}
}
private void BindSecondaryGrid()
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
gvSelected.DataSource = dt;
gvSelected.DataBind();
}
private void BindPrimaryGrid()
{
DataTable dt = new DataTable();
adp = new NpgsqlDataAdapter("select user_id, username,screen_name from users", conn);
dt = new DataTable("users");
adp.Fill(dt);
gvAll.DataSource = dt;
gvAll.DataBind();
After the selection of the data & button click as
protected void btnSubmit_Click(object sender, EventArgs e)
{
GetData();
SetData();
BindSecondaryGrid();
}
private void GetData()
{
DataTable dt;
if (ViewState["SelectedRecords"] != null)
dt = (DataTable)ViewState["SelectedRecords"];
else
dt = CreateDataTable();
CheckBox chkAll = (CheckBox)gvAll.HeaderRow
.Cells[0].FindControl("chkAll");
for (int i = 0; i < gvAll.Rows.Count; i++)
{
if (chkAll.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
}
else
{
CheckBox chk = (CheckBox)gvAll.Rows[i]
.Cells[0].FindControl("chk");
if (chk.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
}
else
{
dt = RemoveRow(gvAll.Rows[i], dt);
}
}
}
ViewState["SelectedRecords"] = dt;
}
private void SetData()
{
CheckBox chkAll = (CheckBox)gvAll.HeaderRow.Cells[0].FindControl("chkAll");
chkAll.Checked = true;
if (ViewState["SelectedRecords"] != null)
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
for (int i = 0; i < gvAll.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gvAll.Rows[i].Cells[0].FindControl("chk");
if (chk != null)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvAll.Rows[i].Cells[1].Text + "'");
chk.Checked = dr.Length > 0;
if (!chk.Checked)
{
chkAll.Checked = false;
}
}
}
}
}
Here while binding the data in function
btnSubmit_Click via
BindSecondaryGrid() showing an error on
gvSelected.DataBind(); in function
BindSecondaryGrid().
Error: DataBinding: 'HttpException - System.Data.DataRowView' does not contain a property with the name 'user_id'.
Edit: Add & Remove Codes
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["CustomerID"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["ContactName"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["Complete Name"] = gvRow.Cells[3].Text;
dt.AcceptChanges();
}
return dt;
}
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}